csharp_script.cpp 49 KB

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