csharp_script.cpp 47 KB

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