csharp_script.cpp 50 KB

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