csharp_script.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  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. void CSharpLanguage::frame() {
  373. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle;
  374. if (task_scheduler_handle.is_valid()) {
  375. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  376. if (task_scheduler) {
  377. GDMonoUtils::GodotTaskScheduler_Activate thunk = CACHED_METHOD_THUNK(GodotTaskScheduler, Activate);
  378. ERR_FAIL_NULL(thunk);
  379. MonoObject *ex;
  380. thunk(task_scheduler, &ex);
  381. if (ex) {
  382. mono_print_unhandled_exception(ex);
  383. ERR_FAIL();
  384. }
  385. }
  386. }
  387. }
  388. struct CSharpScriptDepSort {
  389. // must support sorting so inheritance works properly (parent must be reloaded first)
  390. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  391. if (A == B)
  392. return false; // shouldn't happen but..
  393. GDMonoClass *I = B->base;
  394. while (I) {
  395. if (I == A->script_class) {
  396. // A is a base of B
  397. return true;
  398. }
  399. I = I->get_parent_class();
  400. }
  401. return false; // not a base
  402. }
  403. };
  404. void CSharpLanguage::reload_all_scripts() {
  405. #ifdef DEBUG_ENABLED
  406. #ifndef NO_THREADS
  407. lock->lock();
  408. #endif
  409. List<Ref<CSharpScript> > scripts;
  410. SelfList<CSharpScript> *elem = script_list.first();
  411. while (elem) {
  412. if (elem->self()->get_path().is_resource_file()) {
  413. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  414. }
  415. elem = elem->next();
  416. }
  417. #ifndef NO_THREADS
  418. lock->unlock();
  419. #endif
  420. //as scripts are going to be reloaded, must proceed without locking here
  421. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  422. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  423. E->get()->load_source_code(E->get()->get_path());
  424. E->get()->reload(true);
  425. }
  426. #endif
  427. }
  428. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  429. (void)p_script; // UNUSED
  430. #ifdef TOOLS_ENABLED
  431. MonoReloadNode::get_singleton()->restart_reload_timer();
  432. reload_assemblies_if_needed(p_soft_reload);
  433. #endif
  434. }
  435. #ifdef TOOLS_ENABLED
  436. void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) {
  437. if (gdmono->is_runtime_initialized()) {
  438. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  439. String name = ProjectSettings::get_singleton()->get("application/config/name");
  440. if (name.empty()) {
  441. name = "UnnamedProject";
  442. }
  443. if (proj_assembly) {
  444. String proj_asm_path = proj_assembly->get_path();
  445. if (!FileAccess::exists(proj_assembly->get_path())) {
  446. // Maybe it wasn't loaded from the default path, so check this as well
  447. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name);
  448. if (!FileAccess::exists(proj_asm_path))
  449. return; // No assembly to load
  450. }
  451. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  452. return; // Already up to date
  453. } else {
  454. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name)))
  455. return; // No assembly to load
  456. }
  457. }
  458. #ifndef NO_THREADS
  459. lock->lock();
  460. #endif
  461. List<Ref<CSharpScript> > scripts;
  462. SelfList<CSharpScript> *elem = script_list.first();
  463. while (elem) {
  464. if (elem->self()->get_path().is_resource_file()) {
  465. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to CSharpScript to avoid being erased by accident
  466. }
  467. elem = elem->next();
  468. }
  469. #ifndef NO_THREADS
  470. lock->unlock();
  471. #endif
  472. //when someone asks you why dynamically typed languages are easier to write....
  473. Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  474. //as scripts are going to be reloaded, must proceed without locking here
  475. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  476. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  477. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  478. if (!p_soft_reload) {
  479. //save state and remove script from instances
  480. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  481. while (E->get()->instances.front()) {
  482. Object *obj = E->get()->instances.front()->get();
  483. //save instance info
  484. List<Pair<StringName, Variant> > state;
  485. if (obj->get_script_instance()) {
  486. obj->get_script_instance()->get_property_state(state);
  487. Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle;
  488. if (gchandle.is_valid())
  489. gchandle->release();
  490. map[obj->get_instance_id()] = state;
  491. obj->set_script(RefPtr());
  492. }
  493. }
  494. //same thing for placeholders
  495. while (E->get()->placeholders.size()) {
  496. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  497. //save instance info
  498. List<Pair<StringName, Variant> > state;
  499. if (obj->get_script_instance()) {
  500. obj->get_script_instance()->get_property_state(state);
  501. map[obj->get_instance_id()] = state;
  502. obj->set_script(RefPtr());
  503. }
  504. }
  505. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  506. map[F->key()] = F->get(); //pending to reload, use this one instead
  507. }
  508. E->get()->_clear();
  509. }
  510. }
  511. if (gdmono->reload_scripts_domain() != OK)
  512. return;
  513. for (Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  514. Ref<CSharpScript> scr = E->key();
  515. scr->exports_invalidated = true;
  516. scr->reload(p_soft_reload);
  517. scr->update_exports();
  518. //restore state if saved
  519. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  520. Object *obj = ObjectDB::get_instance(F->key());
  521. if (!obj)
  522. continue;
  523. if (!p_soft_reload) {
  524. //clear it just in case (may be a pending reload state)
  525. obj->set_script(RefPtr());
  526. }
  527. obj->set_script(scr.get_ref_ptr());
  528. if (!obj->get_script_instance()) {
  529. //failed, save reload state for next time if not saved
  530. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  531. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  532. }
  533. continue;
  534. }
  535. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  536. obj->get_script_instance()->set(G->get().first, G->get().second);
  537. }
  538. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  539. }
  540. //if instance states were saved, set them!
  541. }
  542. if (Engine::get_singleton()->is_editor_hint())
  543. EditorNode::get_singleton()->get_property_editor()->update_tree();
  544. }
  545. #endif
  546. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  547. p_extensions->push_back("cs");
  548. }
  549. #ifdef TOOLS_ENABLED
  550. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  551. return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col);
  552. }
  553. bool CSharpLanguage::overrides_external_editor() {
  554. return GodotSharpEditor::get_singleton()->overrides_external_editor();
  555. }
  556. #endif
  557. void CSharpLanguage::thread_enter() {
  558. #if 0
  559. if (mono->is_runtime_initialized()) {
  560. GDMonoUtils::attach_current_thread();
  561. }
  562. #endif
  563. }
  564. void CSharpLanguage::thread_exit() {
  565. #if 0
  566. if (mono->is_runtime_initialized()) {
  567. GDMonoUtils::detach_current_thread();
  568. }
  569. #endif
  570. }
  571. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  572. // Break because of parse error
  573. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  574. // TODO
  575. //_debug_parse_err_line = p_line;
  576. //_debug_parse_err_file = p_file;
  577. //_debug_error = p_error;
  578. ScriptDebugger::get_singleton()->debug(this, false);
  579. return true;
  580. } else {
  581. return false;
  582. }
  583. }
  584. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  585. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  586. // TODO
  587. //_debug_parse_err_line = -1;
  588. //_debug_parse_err_file = "";
  589. //_debug_error = p_error;
  590. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  591. return true;
  592. } else {
  593. return false;
  594. }
  595. }
  596. void CSharpLanguage::set_language_index(int p_idx) {
  597. ERR_FAIL_COND(lang_idx != -1);
  598. lang_idx = p_idx;
  599. }
  600. CSharpLanguage::CSharpLanguage() {
  601. ERR_FAIL_COND(singleton);
  602. singleton = this;
  603. finalizing = false;
  604. gdmono = NULL;
  605. #ifdef NO_THREADS
  606. lock = NULL;
  607. gchandle_bind_lock = NULL;
  608. #else
  609. lock = Mutex::create();
  610. script_bind_lock = Mutex::create();
  611. #endif
  612. lang_idx = -1;
  613. }
  614. CSharpLanguage::~CSharpLanguage() {
  615. finish();
  616. if (lock) {
  617. memdelete(lock);
  618. lock = NULL;
  619. }
  620. if (script_bind_lock) {
  621. memdelete(script_bind_lock);
  622. script_bind_lock = NULL;
  623. }
  624. singleton = NULL;
  625. }
  626. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  627. #ifdef DEBUG_ENABLED
  628. // I don't trust you
  629. if (p_object->get_script_instance())
  630. CRASH_COND(NULL != CAST_CSHARP_INSTANCE(p_object->get_script_instance()));
  631. #endif
  632. StringName type_name = p_object->get_class_name();
  633. // ¯\_(ツ)_/¯
  634. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  635. while (classinfo && !classinfo->exposed)
  636. classinfo = classinfo->inherits_ptr;
  637. ERR_FAIL_NULL_V(classinfo, NULL);
  638. type_name = classinfo->name;
  639. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  640. ERR_FAIL_NULL_V(type_class, NULL);
  641. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  642. ERR_FAIL_NULL_V(mono_object, NULL);
  643. // Tie managed to unmanaged
  644. Reference *ref = Object::cast_to<Reference>(p_object);
  645. if (ref) {
  646. // Unsafe refcount increment. The managed instance also counts as a reference.
  647. // This way if the unmanaged world has no references to our owner
  648. // but the managed instance is alive, the refcount will be 1 instead of 0.
  649. // See: _GodotSharp::_dispose_object(Object *p_object)
  650. ref->reference();
  651. }
  652. Ref<MonoGCHandle> gchandle = MonoGCHandle::create_strong(mono_object);
  653. #ifndef NO_THREADS
  654. script_bind_lock->lock();
  655. #endif
  656. void *data = (void *)gchandle_bindings.insert(p_object, gchandle);
  657. #ifndef NO_THREADS
  658. script_bind_lock->unlock();
  659. #endif
  660. return data;
  661. }
  662. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  663. if (GDMono::get_singleton() == NULL) {
  664. #ifdef DEBUG_ENABLED
  665. CRASH_COND(!gchandle_bindings.empty());
  666. #endif
  667. // Mono runtime finalized, all the gchandle bindings were already released
  668. return;
  669. }
  670. if (finalizing)
  671. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  672. #ifndef NO_THREADS
  673. script_bind_lock->lock();
  674. #endif
  675. Map<Object *, Ref<MonoGCHandle> >::Element *data = (Map<Object *, Ref<MonoGCHandle> >::Element *)p_data;
  676. // Set the native instance field to IntPtr.Zero, if not yet garbage collected
  677. MonoObject *mono_object = data->value()->get_target();
  678. if (mono_object) {
  679. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  680. }
  681. gchandle_bindings.erase(data);
  682. #ifndef NO_THREADS
  683. script_bind_lock->unlock();
  684. #endif
  685. }
  686. void CSharpInstance::_ml_call_reversed(MonoObject *p_mono_object, GDMonoClass *p_klass, const StringName &p_method, const Variant **p_args, int p_argcount) {
  687. GDMonoClass *base = p_klass->get_parent_class();
  688. if (base && base != script->native)
  689. _ml_call_reversed(p_mono_object, base, p_method, p_args, p_argcount);
  690. GDMonoMethod *method = p_klass->get_method(p_method, p_argcount);
  691. if (method) {
  692. method->invoke(p_mono_object, p_args);
  693. }
  694. }
  695. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  696. CSharpInstance *instance = memnew(CSharpInstance);
  697. Reference *ref = Object::cast_to<Reference>(p_owner);
  698. instance->base_ref = ref != NULL;
  699. instance->script = Ref<CSharpScript>(p_script);
  700. instance->owner = p_owner;
  701. instance->gchandle = p_gchandle;
  702. if (instance->base_ref)
  703. instance->_reference_owner_unsafe();
  704. p_script->instances.insert(p_owner);
  705. return instance;
  706. }
  707. MonoObject *CSharpInstance::get_mono_object() const {
  708. #ifdef DEBUG_ENABLED
  709. CRASH_COND(gchandle.is_null());
  710. #endif
  711. return gchandle->get_target();
  712. }
  713. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  714. ERR_FAIL_COND_V(!script.is_valid(), false);
  715. MonoObject *mono_object = get_mono_object();
  716. ERR_FAIL_NULL_V(mono_object, false);
  717. GDMonoClass *top = script->script_class;
  718. while (top && top != script->native) {
  719. GDMonoField *field = script->script_class->get_field(p_name);
  720. if (field) {
  721. field->set_value_from_variant(mono_object, p_value);
  722. return true;
  723. }
  724. GDMonoProperty *property = script->script_class->get_property(p_name);
  725. if (property) {
  726. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value));
  727. return true;
  728. }
  729. top = top->get_parent_class();
  730. }
  731. // Call _set
  732. top = script->script_class;
  733. while (top && top != script->native) {
  734. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  735. if (method) {
  736. Variant name = p_name;
  737. const Variant *args[2] = { &name, &p_value };
  738. MonoObject *ret = method->invoke(mono_object, args);
  739. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret) == true)
  740. return true;
  741. }
  742. top = top->get_parent_class();
  743. }
  744. return false;
  745. }
  746. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  747. ERR_FAIL_COND_V(!script.is_valid(), false);
  748. MonoObject *mono_object = get_mono_object();
  749. ERR_FAIL_NULL_V(mono_object, false);
  750. GDMonoClass *top = script->script_class;
  751. while (top && top != script->native) {
  752. GDMonoField *field = top->get_field(p_name);
  753. if (field) {
  754. MonoObject *value = field->get_value(mono_object);
  755. r_ret = GDMonoMarshal::mono_object_to_variant(value, field->get_type());
  756. return true;
  757. }
  758. GDMonoProperty *property = top->get_property(p_name);
  759. if (property) {
  760. MonoObject *exc = NULL;
  761. MonoObject *value = property->get_value(mono_object, &exc);
  762. if (exc) {
  763. r_ret = Variant();
  764. GDMonoUtils::print_unhandled_exception(exc);
  765. } else {
  766. r_ret = GDMonoMarshal::mono_object_to_variant(value, property->get_type());
  767. }
  768. return true;
  769. }
  770. top = top->get_parent_class();
  771. }
  772. // Call _get
  773. top = script->script_class;
  774. while (top && top != script->native) {
  775. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  776. if (method) {
  777. Variant name = p_name;
  778. const Variant *args[1] = { &name };
  779. MonoObject *ret = method->invoke(mono_object, args);
  780. if (ret) {
  781. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  782. return true;
  783. }
  784. }
  785. top = top->get_parent_class();
  786. }
  787. return false;
  788. }
  789. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  790. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  791. p_properties->push_back(E->value());
  792. }
  793. }
  794. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  795. if (script->member_info.has(p_name)) {
  796. if (r_is_valid)
  797. *r_is_valid = true;
  798. return script->member_info[p_name].type;
  799. }
  800. if (r_is_valid)
  801. *r_is_valid = false;
  802. return Variant::NIL;
  803. }
  804. bool CSharpInstance::has_method(const StringName &p_method) const {
  805. if (!script.is_valid())
  806. return false;
  807. GDMonoClass *top = script->script_class;
  808. while (top && top != script->native) {
  809. if (top->has_method(p_method)) {
  810. return true;
  811. }
  812. top = top->get_parent_class();
  813. }
  814. return false;
  815. }
  816. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  817. MonoObject *mono_object = get_mono_object();
  818. ERR_FAIL_NULL_V(mono_object, Variant());
  819. if (!script.is_valid())
  820. return Variant();
  821. GDMonoClass *top = script->script_class;
  822. while (top && top != script->native) {
  823. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  824. if (method) {
  825. MonoObject *return_value = method->invoke(mono_object, p_args);
  826. if (return_value) {
  827. return GDMonoMarshal::mono_object_to_variant(return_value, method->get_return_type());
  828. } else {
  829. return Variant();
  830. }
  831. }
  832. top = top->get_parent_class();
  833. }
  834. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  835. return Variant();
  836. }
  837. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  838. if (script.is_valid()) {
  839. MonoObject *mono_object = get_mono_object();
  840. ERR_FAIL_NULL(mono_object);
  841. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  842. }
  843. }
  844. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  845. GDMonoClass *top = script->script_class;
  846. while (top && top != script->native) {
  847. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  848. if (method)
  849. method->invoke(p_mono_object, p_args);
  850. top = top->get_parent_class();
  851. }
  852. }
  853. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  854. if (script.is_valid()) {
  855. MonoObject *mono_object = get_mono_object();
  856. ERR_FAIL_NULL(mono_object);
  857. _ml_call_reversed(mono_object, script->script_class, p_method, p_args, p_argcount);
  858. }
  859. }
  860. void CSharpInstance::_reference_owner_unsafe() {
  861. #ifdef DEBUG_ENABLED
  862. CRASH_COND(!base_ref);
  863. #endif
  864. // Unsafe refcount increment. The managed instance also counts as a reference.
  865. // This way if the unmanaged world has no references to our owner
  866. // but the managed instance is alive, the refcount will be 1 instead of 0.
  867. // See: _unreference_owner_unsafe()
  868. // May not me referenced yet, so we must use init_ref() instead of reference()
  869. Object::cast_to<Reference>(owner)->init_ref();
  870. }
  871. void CSharpInstance::_unreference_owner_unsafe() {
  872. #ifdef DEBUG_ENABLED
  873. CRASH_COND(!base_ref);
  874. #endif
  875. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  876. // Unsafe refcount decrement. The managed instance also counts as a reference.
  877. // See: _reference_owner_unsafe()
  878. if (Object::cast_to<Reference>(owner)->unreference()) {
  879. memdelete(owner);
  880. owner = NULL;
  881. }
  882. }
  883. void CSharpInstance::mono_object_disposed() {
  884. if (base_ref)
  885. _unreference_owner_unsafe();
  886. }
  887. void CSharpInstance::refcount_incremented() {
  888. CRASH_COND(!base_ref);
  889. Reference *ref_owner = Object::cast_to<Reference>(owner);
  890. if (ref_owner->reference_get_count() > 1) { // The managed side also holds a reference, hence 1 instead of 0
  891. // The reference count was increased after the managed side was the only one referencing our owner.
  892. // This means the owner is being referenced again by the unmanaged side,
  893. // so the owner must hold the managed side alive again to avoid it from being GCed.
  894. // Release the current weak handle and replace it with a strong handle.
  895. uint32_t strong_gchandle = MonoGCHandle::make_strong_handle(gchandle->get_target());
  896. gchandle->release();
  897. gchandle->set_handle(strong_gchandle);
  898. }
  899. }
  900. bool CSharpInstance::refcount_decremented() {
  901. CRASH_COND(!base_ref);
  902. Reference *ref_owner = Object::cast_to<Reference>(owner);
  903. int refcount = ref_owner->reference_get_count();
  904. if (refcount == 1) { // The managed side also holds a reference, hence 1 instead of 0
  905. // If owner owner is no longer referenced by the unmanaged side,
  906. // the managed instance takes responsibility of deleting the owner when GCed.
  907. // Release the current strong handle and replace it with a weak handle.
  908. uint32_t weak_gchandle = MonoGCHandle::make_weak_handle(gchandle->get_target());
  909. gchandle->release();
  910. gchandle->set_handle(weak_gchandle);
  911. return false;
  912. }
  913. ref_dying = (refcount == 0);
  914. return ref_dying;
  915. }
  916. ScriptInstance::RPCMode CSharpInstance::_member_get_rpc_mode(GDMonoClassMember *p_member) const {
  917. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  918. return RPC_MODE_REMOTE;
  919. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  920. return RPC_MODE_SYNC;
  921. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  922. return RPC_MODE_MASTER;
  923. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  924. return RPC_MODE_SLAVE;
  925. return RPC_MODE_DISABLED;
  926. }
  927. ScriptInstance::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  928. GDMonoClass *top = script->script_class;
  929. while (top && top != script->native) {
  930. GDMonoMethod *method = top->get_method(p_method);
  931. if (method && !method->is_static())
  932. return _member_get_rpc_mode(method);
  933. top = top->get_parent_class();
  934. }
  935. return RPC_MODE_DISABLED;
  936. }
  937. ScriptInstance::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  938. GDMonoClass *top = script->script_class;
  939. while (top && top != script->native) {
  940. GDMonoField *field = top->get_field(p_variable);
  941. if (field && !field->is_static())
  942. return _member_get_rpc_mode(field);
  943. GDMonoProperty *property = top->get_property(p_variable);
  944. if (property && !property->is_static())
  945. return _member_get_rpc_mode(property);
  946. top = top->get_parent_class();
  947. }
  948. return RPC_MODE_DISABLED;
  949. }
  950. void CSharpInstance::notification(int p_notification) {
  951. MonoObject *mono_object = get_mono_object();
  952. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  953. if (mono_object != NULL) { // otherwise it was collected, and the finalizer already called NOTIFICATION_PREDELETE
  954. call_notification_no_check(mono_object, p_notification);
  955. // Set the native instance field to IntPtr.Zero
  956. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  957. }
  958. return;
  959. }
  960. call_notification_no_check(mono_object, p_notification);
  961. }
  962. void CSharpInstance::call_notification_no_check(MonoObject *p_mono_object, int p_notification) {
  963. Variant value = p_notification;
  964. const Variant *args[1] = { &value };
  965. _call_multilevel(p_mono_object, CACHED_STRING_NAME(_notification), args, 1);
  966. }
  967. Ref<Script> CSharpInstance::get_script() const {
  968. return script;
  969. }
  970. ScriptLanguage *CSharpInstance::get_language() {
  971. return CSharpLanguage::get_singleton();
  972. }
  973. CSharpInstance::CSharpInstance() {
  974. owner = NULL;
  975. base_ref = false;
  976. ref_dying = false;
  977. }
  978. CSharpInstance::~CSharpInstance() {
  979. if (gchandle.is_valid()) {
  980. gchandle->release(); // Make sure it's released
  981. }
  982. if (base_ref && !ref_dying) { // it may be called from the owner's destructor
  983. #ifdef DEBUG_ENABLED
  984. CRASH_COND(!owner); // dunno, just in case
  985. #endif
  986. _unreference_owner_unsafe();
  987. }
  988. if (script.is_valid() && owner) {
  989. #ifndef NO_THREADS
  990. CSharpLanguage::singleton->lock->lock();
  991. #endif
  992. #ifdef DEBUG_ENABLED
  993. // CSharpInstance must not be created unless it's going to be added to the list for sure
  994. Set<Object *>::Element *match = script->instances.find(owner);
  995. CRASH_COND(!match);
  996. script->instances.erase(match);
  997. #else
  998. script->instances.erase(owner);
  999. #endif
  1000. #ifndef NO_THREADS
  1001. CSharpLanguage::singleton->lock->unlock();
  1002. #endif
  1003. }
  1004. }
  1005. #ifdef TOOLS_ENABLED
  1006. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1007. placeholders.erase(p_placeholder);
  1008. }
  1009. #endif
  1010. #ifdef TOOLS_ENABLED
  1011. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1012. if (base_cache.is_valid()) {
  1013. base_cache->_update_exports_values(values, propnames);
  1014. }
  1015. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1016. values[E->key()] = E->get();
  1017. }
  1018. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1019. propnames.push_back(E->get());
  1020. }
  1021. }
  1022. #endif
  1023. bool CSharpScript::_update_exports() {
  1024. #ifdef TOOLS_ENABLED
  1025. if (!valid)
  1026. return false;
  1027. bool changed = false;
  1028. if (exports_invalidated) {
  1029. exports_invalidated = false;
  1030. changed = true;
  1031. member_info.clear();
  1032. exported_members_cache.clear();
  1033. exported_members_defval_cache.clear();
  1034. // We are creating a temporary new instance of the class here to get the default value
  1035. // TODO Workaround. Should be replaced with IL opcodes analysis
  1036. MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1037. if (tmp_object) {
  1038. CACHED_FIELD(GodotObject, ptr)->set_value_raw(tmp_object, tmp_object); // FIXME WTF is this workaround
  1039. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1040. MonoObject *ex = NULL;
  1041. ctor->invoke(tmp_object, NULL, &ex);
  1042. if (ex) {
  1043. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1044. mono_print_unhandled_exception(ex);
  1045. tmp_object = NULL;
  1046. ERR_FAIL_V(false);
  1047. }
  1048. } else {
  1049. ERR_PRINT("Failed to create temporary MonoObject");
  1050. return false;
  1051. }
  1052. GDMonoClass *top = script_class;
  1053. while (top && top != native) {
  1054. PropertyInfo prop_info;
  1055. bool exported;
  1056. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1057. for (int i = fields.size() - 1; i >= 0; i--) {
  1058. GDMonoField *field = fields[i];
  1059. if (_get_member_export(top, field, prop_info, exported)) {
  1060. StringName name = field->get_name();
  1061. if (exported) {
  1062. member_info[name] = prop_info;
  1063. exported_members_cache.push_front(prop_info);
  1064. if (tmp_object) {
  1065. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1066. }
  1067. } else {
  1068. member_info[name] = prop_info;
  1069. }
  1070. }
  1071. }
  1072. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1073. for (int i = properties.size() - 1; i >= 0; i--) {
  1074. GDMonoProperty *property = properties[i];
  1075. if (_get_member_export(top, property, prop_info, exported)) {
  1076. StringName name = property->get_name();
  1077. if (exported) {
  1078. member_info[name] = prop_info;
  1079. exported_members_cache.push_front(prop_info);
  1080. if (tmp_object) {
  1081. MonoObject *exc = NULL;
  1082. MonoObject *ret = property->get_value(tmp_object, &exc);
  1083. if (exc) {
  1084. exported_members_defval_cache[name] = Variant();
  1085. GDMonoUtils::print_unhandled_exception(exc);
  1086. } else {
  1087. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret);
  1088. }
  1089. }
  1090. } else {
  1091. member_info[name] = prop_info;
  1092. }
  1093. }
  1094. }
  1095. top = top->get_parent_class();
  1096. }
  1097. }
  1098. if (placeholders.size()) {
  1099. // Update placeholders if any
  1100. Map<StringName, Variant> values;
  1101. List<PropertyInfo> propnames;
  1102. _update_exports_values(values, propnames);
  1103. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1104. E->get()->update(propnames, values);
  1105. }
  1106. }
  1107. return changed;
  1108. #endif
  1109. return false;
  1110. }
  1111. bool CSharpScript::_get_member_export(GDMonoClass *p_class, GDMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) {
  1112. StringName name = p_member->get_name();
  1113. if (p_member->is_static()) {
  1114. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1115. ERR_PRINTS("Cannot export member because it is static: " + p_class->get_full_name() + "." + name.operator String());
  1116. return false;
  1117. }
  1118. if (member_info.has(name))
  1119. return false;
  1120. ManagedType type;
  1121. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_FIELD) {
  1122. type = static_cast<GDMonoField *>(p_member)->get_type();
  1123. } else if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1124. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1125. } else {
  1126. CRASH_NOW();
  1127. }
  1128. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1129. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
  1130. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1131. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1132. if (!property->has_getter() || !property->has_setter()) {
  1133. ERR_PRINTS("Cannot export property because it does not provide a getter or a setter: " + p_class->get_full_name() + "." + name.operator String());
  1134. return false;
  1135. }
  1136. }
  1137. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1138. PropertyHint hint;
  1139. String hint_string;
  1140. if (variant_type == Variant::NIL) {
  1141. ERR_PRINTS("Unknown type of exported member: " + p_class->get_full_name() + "." + name.operator String());
  1142. return false;
  1143. } else if (variant_type == Variant::INT && type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(type.type_class->get_mono_ptr())) {
  1144. variant_type = Variant::INT;
  1145. hint = PROPERTY_HINT_ENUM;
  1146. Vector<MonoClassField *> fields = type.type_class->get_enum_fields();
  1147. for (int i = 0; i < fields.size(); i++) {
  1148. if (i > 0)
  1149. hint_string += ",";
  1150. hint_string += mono_field_get_name(fields[i]);
  1151. }
  1152. } else if (variant_type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(type.type_class)) {
  1153. hint = PROPERTY_HINT_RESOURCE_TYPE;
  1154. hint_string = NATIVE_GDMONOCLASS_NAME(type.type_class);
  1155. } else {
  1156. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1157. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1158. }
  1159. r_prop_info = PropertyInfo(variant_type, name.operator String(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1160. r_exported = true;
  1161. } else {
  1162. r_prop_info = PropertyInfo(variant_type, name.operator String(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1163. r_exported = false;
  1164. }
  1165. return true;
  1166. }
  1167. void CSharpScript::_clear() {
  1168. tool = false;
  1169. valid = false;
  1170. base = NULL;
  1171. native = NULL;
  1172. script_class = NULL;
  1173. }
  1174. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1175. GDMonoClass *top = script_class;
  1176. while (top && top != native) {
  1177. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1178. if (method && method->is_static()) {
  1179. MonoObject *result = method->invoke(NULL, p_args);
  1180. if (result) {
  1181. return GDMonoMarshal::mono_object_to_variant(result, method->get_return_type());
  1182. } else {
  1183. return Variant();
  1184. }
  1185. }
  1186. top = top->get_parent_class();
  1187. }
  1188. // No static method found. Try regular instance calls
  1189. return Script::call(p_method, p_args, p_argcount, r_error);
  1190. }
  1191. void CSharpScript::_resource_path_changed() {
  1192. String path = get_path();
  1193. if (!path.empty()) {
  1194. name = get_path().get_file().get_basename();
  1195. }
  1196. }
  1197. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1198. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1199. r_ret = get_source_code();
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1205. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1206. set_source_code(p_value);
  1207. reload();
  1208. return true;
  1209. }
  1210. return false;
  1211. }
  1212. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1213. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
  1214. }
  1215. void CSharpScript::_bind_methods() {
  1216. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
  1217. }
  1218. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class) {
  1219. // This method should not fail
  1220. CRASH_COND(!p_class);
  1221. Ref<CSharpScript> script = memnew(CSharpScript);
  1222. script->name = p_class->get_name();
  1223. script->script_class = p_class;
  1224. script->native = GDMonoUtils::get_class_native_base(script->script_class);
  1225. CRASH_COND(script->native == NULL);
  1226. GDMonoClass *base = script->script_class->get_parent_class();
  1227. if (base != script->native)
  1228. script->base = base;
  1229. #ifdef DEBUG_ENABLED
  1230. // For debug builds, we must fetch from all native base methods as well.
  1231. // Native base methods must be fetched before the current class.
  1232. // Not needed if the script class itself is a native class.
  1233. if (script->script_class != script->native) {
  1234. GDMonoClass *native_top = script->native;
  1235. while (native_top) {
  1236. native_top->fetch_methods_with_godot_api_checks(script->native);
  1237. if (native_top == CACHED_CLASS(GodotObject))
  1238. break;
  1239. native_top = native_top->get_parent_class();
  1240. }
  1241. }
  1242. #endif
  1243. script->script_class->fetch_methods_with_godot_api_checks(script->native);
  1244. // Need to fetch method from base classes as well
  1245. GDMonoClass *top = script->script_class;
  1246. while (top && top != script->native) {
  1247. top->fetch_methods_with_godot_api_checks(script->native);
  1248. top = top->get_parent_class();
  1249. }
  1250. return script;
  1251. }
  1252. bool CSharpScript::can_instance() const {
  1253. #ifdef TOOLS_ENABLED
  1254. if (Engine::get_singleton()->is_editor_hint()) {
  1255. if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  1256. if (_create_project_solution_if_needed()) {
  1257. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1258. "Compile",
  1259. ProjectSettings::get_singleton()->globalize_path(get_path()));
  1260. } else {
  1261. ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created.");
  1262. }
  1263. }
  1264. }
  1265. #endif
  1266. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  1267. }
  1268. StringName CSharpScript::get_instance_base_type() const {
  1269. if (native)
  1270. return native->get_name();
  1271. else
  1272. return StringName();
  1273. }
  1274. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  1275. /* STEP 1, CREATE */
  1276. CSharpInstance *instance = memnew(CSharpInstance);
  1277. instance->base_ref = p_isref;
  1278. instance->script = Ref<CSharpScript>(this);
  1279. instance->owner = p_owner;
  1280. instance->owner->set_script_instance(instance);
  1281. if (instance->base_ref)
  1282. instance->_reference_owner_unsafe();
  1283. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1284. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1285. if (!mono_object) {
  1286. instance->script = Ref<CSharpScript>();
  1287. instance->owner->set_script_instance(NULL);
  1288. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1289. ERR_EXPLAIN("Failed to allocate memory for the object");
  1290. ERR_FAIL_V(NULL);
  1291. }
  1292. #ifndef NO_THREADS
  1293. CSharpLanguage::singleton->lock->lock();
  1294. #endif
  1295. instances.insert(instance->owner);
  1296. #ifndef NO_THREADS
  1297. CSharpLanguage::singleton->lock->unlock();
  1298. #endif
  1299. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  1300. // Construct
  1301. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  1302. ctor->invoke(mono_object, p_args, NULL);
  1303. // Tie managed to unmanaged
  1304. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  1305. /* STEP 3, PARTY */
  1306. //@TODO make thread safe
  1307. return instance;
  1308. }
  1309. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1310. if (!valid) {
  1311. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1312. return Variant();
  1313. }
  1314. r_error.error = Variant::CallError::CALL_OK;
  1315. REF ref;
  1316. Object *owner = NULL;
  1317. ERR_FAIL_NULL_V(native, Variant());
  1318. owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  1319. Reference *r = Object::cast_to<Reference>(owner);
  1320. if (r) {
  1321. ref = REF(r);
  1322. }
  1323. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  1324. if (!instance) {
  1325. if (ref.is_null()) {
  1326. memdelete(owner); //no owner, sorry
  1327. }
  1328. return Variant();
  1329. }
  1330. if (ref.is_valid()) {
  1331. return ref;
  1332. } else {
  1333. return owner;
  1334. }
  1335. }
  1336. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1337. if (!valid)
  1338. return NULL;
  1339. if (!tool && !ScriptServer::is_scripting_enabled()) {
  1340. #ifdef TOOLS_ENABLED
  1341. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1342. placeholders.insert(si);
  1343. _update_exports();
  1344. return si;
  1345. #else
  1346. return NULL;
  1347. #endif
  1348. }
  1349. if (native) {
  1350. String native_name = native->get_name();
  1351. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1352. if (ScriptDebugger::get_singleton()) {
  1353. 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() + "'");
  1354. }
  1355. ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  1356. ERR_FAIL_V(NULL);
  1357. }
  1358. }
  1359. Variant::CallError unchecked_error;
  1360. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  1361. }
  1362. bool CSharpScript::instance_has(const Object *p_this) const {
  1363. #ifndef NO_THREADS
  1364. CSharpLanguage::singleton->lock->lock();
  1365. #endif
  1366. bool ret = instances.has((Object *)p_this);
  1367. #ifndef NO_THREADS
  1368. CSharpLanguage::singleton->lock->unlock();
  1369. #endif
  1370. return ret;
  1371. }
  1372. bool CSharpScript::has_source_code() const {
  1373. return !source.empty();
  1374. }
  1375. String CSharpScript::get_source_code() const {
  1376. return source;
  1377. }
  1378. void CSharpScript::set_source_code(const String &p_code) {
  1379. if (source == p_code)
  1380. return;
  1381. source = p_code;
  1382. #ifdef TOOLS_ENABLED
  1383. source_changed_cache = true;
  1384. #endif
  1385. }
  1386. bool CSharpScript::has_method(const StringName &p_method) const {
  1387. return script_class->has_method(p_method);
  1388. }
  1389. Error CSharpScript::reload(bool p_keep_state) {
  1390. #ifndef NO_THREADS
  1391. CSharpLanguage::singleton->lock->lock();
  1392. #endif
  1393. bool has_instances = instances.size();
  1394. #ifndef NO_THREADS
  1395. CSharpLanguage::singleton->lock->unlock();
  1396. #endif
  1397. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  1398. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  1399. if (project_assembly) {
  1400. script_class = project_assembly->get_object_derived_class(name);
  1401. if (!script_class) {
  1402. ERR_PRINTS("Cannot find class " + name + " for script " + get_path());
  1403. }
  1404. #ifdef DEBUG_ENABLED
  1405. else if (OS::get_singleton()->is_stdout_verbose()) {
  1406. OS::get_singleton()->print(String("Found class " + script_class->get_namespace() + "." +
  1407. script_class->get_name() + " for script " + get_path() + "\n")
  1408. .utf8());
  1409. }
  1410. #endif
  1411. valid = script_class != NULL;
  1412. if (script_class) {
  1413. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  1414. native = GDMonoUtils::get_class_native_base(script_class);
  1415. CRASH_COND(native == NULL);
  1416. GDMonoClass *base_class = script_class->get_parent_class();
  1417. if (base_class != native)
  1418. base = base_class;
  1419. #ifdef DEBUG_ENABLED
  1420. // For debug builds, we must fetch from all native base methods as well.
  1421. // Native base methods must be fetched before the current class.
  1422. // Not needed if the script class itself is a native class.
  1423. if (script_class != native) {
  1424. GDMonoClass *native_top = native;
  1425. while (native_top) {
  1426. native_top->fetch_methods_with_godot_api_checks(native);
  1427. if (native_top == CACHED_CLASS(GodotObject))
  1428. break;
  1429. native_top = native_top->get_parent_class();
  1430. }
  1431. }
  1432. #endif
  1433. script_class->fetch_methods_with_godot_api_checks(native);
  1434. // Need to fetch method from base classes as well
  1435. GDMonoClass *top = script_class;
  1436. while (top && top != native) {
  1437. top->fetch_methods_with_godot_api_checks(native);
  1438. top = top->get_parent_class();
  1439. }
  1440. }
  1441. return OK;
  1442. }
  1443. return ERR_FILE_MISSING_DEPENDENCIES;
  1444. }
  1445. ScriptLanguage *CSharpScript::get_language() const {
  1446. return CSharpLanguage::get_singleton();
  1447. }
  1448. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  1449. #ifdef TOOLS_ENABLED
  1450. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  1451. if (E) {
  1452. r_value = E->get();
  1453. return true;
  1454. }
  1455. if (base_cache.is_valid()) {
  1456. return base_cache->get_property_default_value(p_property, r_value);
  1457. }
  1458. #endif
  1459. return false;
  1460. }
  1461. void CSharpScript::update_exports() {
  1462. #ifdef TOOLS_ENABLED
  1463. _update_exports();
  1464. #endif
  1465. }
  1466. Ref<Script> CSharpScript::get_base_script() const {
  1467. // TODO search in metadata file once we have it, not important any way?
  1468. return Ref<Script>();
  1469. }
  1470. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  1471. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  1472. p_list->push_back(E->value());
  1473. }
  1474. }
  1475. int CSharpScript::get_member_line(const StringName &p_member) const {
  1476. // TODO omnisharp
  1477. return -1;
  1478. }
  1479. Error CSharpScript::load_source_code(const String &p_path) {
  1480. PoolVector<uint8_t> sourcef;
  1481. Error err;
  1482. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  1483. ERR_FAIL_COND_V(err != OK, err);
  1484. int len = f->get_len();
  1485. sourcef.resize(len + 1);
  1486. PoolVector<uint8_t>::Write w = sourcef.write();
  1487. int r = f->get_buffer(w.ptr(), len);
  1488. f->close();
  1489. memdelete(f);
  1490. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  1491. w[len] = 0;
  1492. String s;
  1493. if (s.parse_utf8((const char *)w.ptr())) {
  1494. 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.");
  1495. ERR_FAIL_V(ERR_INVALID_DATA);
  1496. }
  1497. source = s;
  1498. #ifdef TOOLS_ENABLED
  1499. source_changed_cache = true;
  1500. #endif
  1501. return OK;
  1502. }
  1503. StringName CSharpScript::get_script_name() const {
  1504. return name;
  1505. }
  1506. CSharpScript::CSharpScript() :
  1507. script_list(this) {
  1508. _clear();
  1509. #ifdef TOOLS_ENABLED
  1510. source_changed_cache = false;
  1511. exports_invalidated = true;
  1512. #endif
  1513. _resource_path_changed();
  1514. #ifdef DEBUG_ENABLED
  1515. #ifndef NO_THREADS
  1516. CSharpLanguage::get_singleton()->lock->lock();
  1517. #endif
  1518. CSharpLanguage::get_singleton()->script_list.add(&script_list);
  1519. #ifndef NO_THREADS
  1520. CSharpLanguage::get_singleton()->lock->unlock();
  1521. #endif
  1522. #endif // DEBUG_ENABLED
  1523. }
  1524. CSharpScript::~CSharpScript() {
  1525. #ifdef DEBUG_ENABLED
  1526. #ifndef NO_THREADS
  1527. CSharpLanguage::get_singleton()->lock->lock();
  1528. #endif
  1529. CSharpLanguage::get_singleton()->script_list.remove(&script_list);
  1530. #ifndef NO_THREADS
  1531. CSharpLanguage::get_singleton()->lock->unlock();
  1532. #endif
  1533. #endif // DEBUG_ENABLED
  1534. }
  1535. /*************** RESOURCE ***************/
  1536. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1537. if (r_error)
  1538. *r_error = ERR_FILE_CANT_OPEN;
  1539. // TODO ignore anything inside bin/ and obj/ in tools builds?
  1540. CSharpScript *script = memnew(CSharpScript);
  1541. Ref<CSharpScript> scriptres(script);
  1542. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  1543. Error err = script->load_source_code(p_path);
  1544. ERR_FAIL_COND_V(err != OK, RES());
  1545. #endif
  1546. script->set_path(p_original_path);
  1547. #ifndef TOOLS_ENABLED
  1548. #ifdef DEBUG_ENABLED
  1549. // User is responsible for thread attach/detach
  1550. ERR_EXPLAIN("Thread is not attached");
  1551. CRASH_COND(mono_domain_get() == NULL);
  1552. #endif
  1553. #else
  1554. if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) {
  1555. CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
  1556. // Thread is not attached, but we will make an exception in this case
  1557. // because this may be called by one of the editor's worker threads.
  1558. // Attach this thread temporarily to reload the script.
  1559. MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
  1560. CRASH_COND(mono_thread == NULL);
  1561. script->reload();
  1562. mono_thread_detach(mono_thread);
  1563. } else // just reload it normally
  1564. #endif
  1565. script->reload();
  1566. if (r_error)
  1567. *r_error = OK;
  1568. return scriptres;
  1569. }
  1570. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  1571. p_extensions->push_back("cs");
  1572. }
  1573. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  1574. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  1575. }
  1576. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  1577. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  1578. }
  1579. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1580. Ref<CSharpScript> sqscr = p_resource;
  1581. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1582. String source = sqscr->get_source_code();
  1583. #ifdef TOOLS_ENABLED
  1584. if (!FileAccess::exists(p_path)) {
  1585. // The file does not yet exists, let's assume the user just created this script
  1586. if (_create_project_solution_if_needed()) {
  1587. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1588. "Compile",
  1589. ProjectSettings::get_singleton()->globalize_path(p_path));
  1590. } else {
  1591. ERR_PRINTS("Cannot add " + p_path + " to the C# project because it could not be created.");
  1592. }
  1593. }
  1594. #endif
  1595. Error err;
  1596. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1597. ERR_FAIL_COND_V(err, err);
  1598. file->store_string(source);
  1599. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1600. memdelete(file);
  1601. return ERR_CANT_CREATE;
  1602. }
  1603. file->close();
  1604. memdelete(file);
  1605. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1606. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1607. }
  1608. return OK;
  1609. }
  1610. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1611. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  1612. p_extensions->push_back("cs");
  1613. }
  1614. }
  1615. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  1616. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  1617. }
  1618. CSharpLanguage::StringNameCache::StringNameCache() {
  1619. _signal_callback = StaticCString::create("_signal_callback");
  1620. _set = StaticCString::create("_set");
  1621. _get = StaticCString::create("_get");
  1622. _notification = StaticCString::create("_notification");
  1623. _script_source = StaticCString::create("script/source");
  1624. dotctor = StaticCString::create(".ctor");
  1625. }