csharp_script.cpp 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "core/io/json.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "core/os/thread.h"
  36. #include "core/project_settings.h"
  37. #ifdef TOOLS_ENABLED
  38. #include "editor/bindings_generator.h"
  39. #include "editor/csharp_project.h"
  40. #include "editor/editor_node.h"
  41. #endif
  42. #include "editor/editor_internal_calls.h"
  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. #include "utils/macros.h"
  48. #include "utils/mutex_utils.h"
  49. #include "utils/string_utils.h"
  50. #include "utils/thread_local.h"
  51. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  52. #ifdef TOOLS_ENABLED
  53. static bool _create_project_solution_if_needed() {
  54. String sln_path = GodotSharpDirs::get_project_sln_path();
  55. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  56. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  57. // A solution does not yet exist, create a new one
  58. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == NULL);
  59. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
  60. }
  61. return true;
  62. }
  63. #endif
  64. CSharpLanguage *CSharpLanguage::singleton = NULL;
  65. String CSharpLanguage::get_name() const {
  66. return "C#";
  67. }
  68. String CSharpLanguage::get_type() const {
  69. return "CSharpScript";
  70. }
  71. String CSharpLanguage::get_extension() const {
  72. return "cs";
  73. }
  74. Error CSharpLanguage::execute_file(const String &p_path) {
  75. // ??
  76. return OK;
  77. }
  78. void CSharpLanguage::init() {
  79. gdmono = memnew(GDMono);
  80. gdmono->initialize();
  81. #ifndef MONO_GLUE_ENABLED
  82. WARN_PRINT("This binary is built with `mono_glue=no` and cannot be used for scripting");
  83. #endif
  84. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  85. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  86. BindingsGenerator::handle_cmdline_args(cmdline_args);
  87. #endif
  88. #ifdef TOOLS_ENABLED
  89. EditorNode::add_init_callback(&_editor_init_callback);
  90. GLOBAL_DEF("mono/export/include_scripts_content", false);
  91. #endif
  92. }
  93. void CSharpLanguage::finish() {
  94. finalizing = true;
  95. // Make sure all script binding gchandles are released before finalizing GDMono
  96. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  97. CSharpScriptBinding &script_binding = E->value();
  98. if (script_binding.gchandle.is_valid()) {
  99. script_binding.gchandle->release();
  100. script_binding.inited = false;
  101. }
  102. }
  103. if (gdmono) {
  104. memdelete(gdmono);
  105. gdmono = NULL;
  106. }
  107. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  108. script_bindings.clear();
  109. finalizing = false;
  110. }
  111. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  112. static const char *_reserved_words[] = {
  113. // Reserved keywords
  114. "abstract",
  115. "as",
  116. "base",
  117. "bool",
  118. "break",
  119. "byte",
  120. "case",
  121. "catch",
  122. "char",
  123. "checked",
  124. "class",
  125. "const",
  126. "continue",
  127. "decimal",
  128. "default",
  129. "delegate",
  130. "do",
  131. "double",
  132. "else",
  133. "enum",
  134. "event",
  135. "explicit",
  136. "extern",
  137. "false",
  138. "finally",
  139. "fixed",
  140. "float",
  141. "for",
  142. "foreach",
  143. "goto",
  144. "if",
  145. "implicit",
  146. "in",
  147. "int",
  148. "interface",
  149. "internal",
  150. "is",
  151. "lock",
  152. "long",
  153. "namespace",
  154. "new",
  155. "null",
  156. "object",
  157. "operator",
  158. "out",
  159. "override",
  160. "params",
  161. "private",
  162. "protected",
  163. "public",
  164. "readonly",
  165. "ref",
  166. "return",
  167. "sbyte",
  168. "sealed",
  169. "short",
  170. "sizeof",
  171. "stackalloc",
  172. "static",
  173. "string",
  174. "struct",
  175. "switch",
  176. "this",
  177. "throw",
  178. "true",
  179. "try",
  180. "typeof",
  181. "uint",
  182. "ulong",
  183. "unchecked",
  184. "unsafe",
  185. "ushort",
  186. "using",
  187. "virtual",
  188. "void",
  189. "volatile",
  190. "while",
  191. // Contextual keywords. Not reserved words, but I guess we should include
  192. // them because this seems to be used only for syntax highlighting.
  193. "add",
  194. "alias",
  195. "ascending",
  196. "async",
  197. "await",
  198. "by",
  199. "descending",
  200. "dynamic",
  201. "equals",
  202. "from",
  203. "get",
  204. "global",
  205. "group",
  206. "into",
  207. "join",
  208. "let",
  209. "nameof",
  210. "on",
  211. "orderby",
  212. "partial",
  213. "remove",
  214. "select",
  215. "set",
  216. "value",
  217. "var",
  218. "when",
  219. "where",
  220. "yield",
  221. 0
  222. };
  223. const char **w = _reserved_words;
  224. while (*w) {
  225. p_words->push_back(*w);
  226. w++;
  227. }
  228. }
  229. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  230. p_delimiters->push_back("//"); // single-line comment
  231. p_delimiters->push_back("/* */"); // delimited comment
  232. }
  233. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  234. p_delimiters->push_back("' '"); // character literal
  235. p_delimiters->push_back("\" \""); // regular string literal
  236. p_delimiters->push_back("@\" \""); // verbatim string literal
  237. }
  238. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  239. String base_class = p_base_class_name;
  240. if (p_class_name == base_class) {
  241. base_class = "Godot." + base_class;
  242. }
  243. return base_class;
  244. }
  245. Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  246. String script_template = "using " BINDINGS_NAMESPACE ";\n"
  247. "using System;\n"
  248. "\n"
  249. "public class %CLASS% : %BASE%\n"
  250. "{\n"
  251. " // Declare member variables here. Examples:\n"
  252. " // private int a = 2;\n"
  253. " // private string b = \"text\";\n"
  254. "\n"
  255. " // Called when the node enters the scene tree for the first time.\n"
  256. " public override void _Ready()\n"
  257. " {\n"
  258. " \n"
  259. " }\n"
  260. "\n"
  261. "// // Called every frame. 'delta' is the elapsed time since the previous frame.\n"
  262. "// public override void _Process(float delta)\n"
  263. "// {\n"
  264. "// \n"
  265. "// }\n"
  266. "}\n";
  267. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  268. script_template = script_template.replace("%BASE%", base_class_name)
  269. .replace("%CLASS%", p_class_name);
  270. Ref<CSharpScript> script;
  271. script.instance();
  272. script->set_source_code(script_template);
  273. script->set_name(p_class_name);
  274. return script;
  275. }
  276. bool CSharpLanguage::is_using_templates() {
  277. return true;
  278. }
  279. void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  280. String src = p_script->get_source_code();
  281. String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
  282. src = src.replace("%BASE%", base_class_name)
  283. .replace("%CLASS%", p_class_name)
  284. .replace("%TS%", _get_indentation());
  285. p_script->set_source_code(src);
  286. }
  287. String CSharpLanguage::validate_path(const String &p_path) const {
  288. String class_name = p_path.get_file().get_basename();
  289. List<String> keywords;
  290. get_reserved_words(&keywords);
  291. if (keywords.find(class_name)) {
  292. return TTR("Class name can't be a reserved keyword");
  293. }
  294. return "";
  295. }
  296. Script *CSharpLanguage::create_script() const {
  297. return memnew(CSharpScript);
  298. }
  299. bool CSharpLanguage::has_named_classes() const {
  300. return false;
  301. }
  302. bool CSharpLanguage::supports_builtin_mode() const {
  303. return false;
  304. }
  305. #ifdef TOOLS_ENABLED
  306. static String variant_type_to_managed_name(const String &p_var_type_name) {
  307. if (p_var_type_name.empty())
  308. return "object";
  309. if (!ClassDB::class_exists(p_var_type_name)) {
  310. return p_var_type_name;
  311. }
  312. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
  313. return "Godot.Object";
  314. if (p_var_type_name == Variant::get_type_name(Variant::REAL)) {
  315. #ifdef REAL_T_IS_DOUBLE
  316. return "double";
  317. #else
  318. return "float";
  319. #endif
  320. }
  321. if (p_var_type_name == Variant::get_type_name(Variant::STRING))
  322. return "string"; // I prefer this one >:[
  323. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
  324. return "Collections.Dictionary";
  325. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
  326. return "Collections.Array";
  327. if (p_var_type_name == Variant::get_type_name(Variant::POOL_BYTE_ARRAY))
  328. return "byte[]";
  329. if (p_var_type_name == Variant::get_type_name(Variant::POOL_INT_ARRAY))
  330. return "int[]";
  331. if (p_var_type_name == Variant::get_type_name(Variant::POOL_REAL_ARRAY)) {
  332. #ifdef REAL_T_IS_DOUBLE
  333. return "double[]";
  334. #else
  335. return "float[]";
  336. #endif
  337. }
  338. if (p_var_type_name == Variant::get_type_name(Variant::POOL_STRING_ARRAY))
  339. return "string[]";
  340. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR2_ARRAY))
  341. return "Vector2[]";
  342. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR3_ARRAY))
  343. return "Vector3[]";
  344. if (p_var_type_name == Variant::get_type_name(Variant::POOL_COLOR_ARRAY))
  345. return "Color[]";
  346. Variant::Type var_types[] = {
  347. Variant::BOOL,
  348. Variant::INT,
  349. Variant::VECTOR2,
  350. Variant::RECT2,
  351. Variant::VECTOR3,
  352. Variant::TRANSFORM2D,
  353. Variant::PLANE,
  354. Variant::QUAT,
  355. Variant::AABB,
  356. Variant::BASIS,
  357. Variant::TRANSFORM,
  358. Variant::COLOR,
  359. Variant::NODE_PATH,
  360. Variant::_RID
  361. };
  362. for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  363. if (p_var_type_name == Variant::get_type_name(var_types[i]))
  364. return p_var_type_name;
  365. }
  366. return "object";
  367. }
  368. String CSharpLanguage::make_function(const String &, const String &p_name, const PoolStringArray &p_args) const {
  369. // FIXME
  370. // - Due to Godot's API limitation this just appends the function to the end of the file
  371. // - Use fully qualified name if there is ambiguity
  372. String s = "private void " + p_name + "(";
  373. for (int i = 0; i < p_args.size(); i++) {
  374. const String &arg = p_args[i];
  375. if (i > 0)
  376. s += ", ";
  377. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  378. }
  379. s += ")\n{\n // Replace with function body.\n}\n";
  380. return s;
  381. }
  382. #else
  383. String CSharpLanguage::make_function(const String &, const String &, const PoolStringArray &) const {
  384. return String();
  385. }
  386. #endif
  387. String CSharpLanguage::_get_indentation() const {
  388. #ifdef TOOLS_ENABLED
  389. if (Engine::get_singleton()->is_editor_hint()) {
  390. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);
  391. if (use_space_indentation) {
  392. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  393. String space_indent = "";
  394. for (int i = 0; i < indent_size; i++) {
  395. space_indent += " ";
  396. }
  397. return space_indent;
  398. }
  399. }
  400. #endif
  401. return "\t";
  402. }
  403. String CSharpLanguage::debug_get_error() const {
  404. return _debug_error;
  405. }
  406. int CSharpLanguage::debug_get_stack_level_count() const {
  407. if (_debug_parse_err_line >= 0)
  408. return 1;
  409. // TODO: StackTrace
  410. return 1;
  411. }
  412. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  413. if (_debug_parse_err_line >= 0)
  414. return _debug_parse_err_line;
  415. // TODO: StackTrace
  416. return 1;
  417. }
  418. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  419. if (_debug_parse_err_line >= 0)
  420. return String();
  421. // TODO: StackTrace
  422. return String();
  423. }
  424. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  425. if (_debug_parse_err_line >= 0)
  426. return _debug_parse_err_file;
  427. // TODO: StackTrace
  428. return String();
  429. }
  430. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  431. #ifdef DEBUG_ENABLED
  432. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  433. if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoUtils::mono_cache.corlib_cache_updated)
  434. return Vector<StackInfo>();
  435. MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
  436. MonoBoolean need_file_info = true;
  437. void *ctor_args[1] = { &need_file_info };
  438. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
  439. Vector<StackInfo> si;
  440. si = stack_trace_get_info(stack_trace);
  441. return si;
  442. #else
  443. return Vector<StackInfo>();
  444. #endif
  445. }
  446. #ifdef DEBUG_ENABLED
  447. Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
  448. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  449. MonoException *exc = NULL;
  450. MonoArray *frames = invoke_method_thunk(CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames), p_stack_trace, &exc);
  451. if (exc) {
  452. GDMonoUtils::debug_print_unhandled_exception(exc);
  453. return Vector<StackInfo>();
  454. }
  455. int frame_count = mono_array_length(frames);
  456. if (frame_count <= 0)
  457. return Vector<StackInfo>();
  458. GDMonoUtils::DebugUtils_StackFrameInfo get_sf_info = CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo);
  459. Vector<StackInfo> si;
  460. si.resize(frame_count);
  461. for (int i = 0; i < frame_count; i++) {
  462. StackInfo &sif = si.write[i];
  463. MonoObject *frame = mono_array_get(frames, MonoObject *, i);
  464. MonoString *file_name;
  465. int file_line_num;
  466. MonoString *method_decl;
  467. invoke_method_thunk(get_sf_info, frame, &file_name, &file_line_num, &method_decl, &exc);
  468. if (exc) {
  469. GDMonoUtils::debug_print_unhandled_exception(exc);
  470. return Vector<StackInfo>();
  471. }
  472. // TODO
  473. // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
  474. // can reproduce with a MissingMethodException on internal calls
  475. sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
  476. sif.line = file_line_num;
  477. sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
  478. }
  479. return si;
  480. }
  481. #endif
  482. void CSharpLanguage::frame() {
  483. if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) {
  484. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle;
  485. if (task_scheduler_handle.is_valid()) {
  486. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  487. if (task_scheduler) {
  488. MonoException *exc = NULL;
  489. invoke_method_thunk(CACHED_METHOD_THUNK(GodotTaskScheduler, Activate), task_scheduler, &exc);
  490. if (exc) {
  491. GDMonoUtils::debug_unhandled_exception(exc);
  492. GD_UNREACHABLE();
  493. }
  494. }
  495. }
  496. }
  497. }
  498. struct CSharpScriptDepSort {
  499. // must support sorting so inheritance works properly (parent must be reloaded first)
  500. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  501. if (A == B)
  502. return false; // shouldn't happen but..
  503. GDMonoClass *I = B->base;
  504. while (I) {
  505. if (I == A->script_class) {
  506. // A is a base of B
  507. return true;
  508. }
  509. I = I->get_parent_class();
  510. }
  511. return false; // not a base
  512. }
  513. };
  514. void CSharpLanguage::reload_all_scripts() {
  515. #ifdef GD_MONO_HOT_RELOAD
  516. if (is_assembly_reloading_needed()) {
  517. reload_assemblies(false);
  518. }
  519. #endif
  520. }
  521. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  522. (void)p_script; // UNUSED
  523. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  524. #ifdef TOOLS_ENABLED
  525. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  526. #endif
  527. #ifdef GD_MONO_HOT_RELOAD
  528. if (is_assembly_reloading_needed()) {
  529. reload_assemblies(p_soft_reload);
  530. }
  531. #endif
  532. }
  533. #ifdef GD_MONO_HOT_RELOAD
  534. bool CSharpLanguage::is_assembly_reloading_needed() {
  535. if (!gdmono->is_runtime_initialized())
  536. return false;
  537. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  538. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  539. String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
  540. if (appname_safe.empty()) {
  541. appname_safe = "UnnamedProject";
  542. }
  543. appname_safe += ".dll";
  544. if (proj_assembly) {
  545. String proj_asm_path = proj_assembly->get_path();
  546. if (!FileAccess::exists(proj_assembly->get_path())) {
  547. // Maybe it wasn't loaded from the default path, so check this as well
  548. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
  549. if (!FileAccess::exists(proj_asm_path))
  550. return false; // No assembly to load
  551. }
  552. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  553. return false; // Already up to date
  554. } else {
  555. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe)))
  556. return false; // No assembly to load
  557. }
  558. #ifdef TOOLS_ENABLED
  559. if (!gdmono->get_core_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE))
  560. return false; // The core API assembly to load is invalidated
  561. if (!gdmono->get_editor_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR))
  562. return false; // The editor API assembly to load is invalidated
  563. #endif
  564. return true;
  565. }
  566. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  567. if (!gdmono->is_runtime_initialized())
  568. return;
  569. // There is no soft reloading with Mono. It's always hard reloading.
  570. List<Ref<CSharpScript> > scripts;
  571. {
  572. SCOPED_MUTEX_LOCK(script_instances_mutex);
  573. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  574. // Cast to CSharpScript to avoid being erased by accident
  575. scripts.push_back(Ref<CSharpScript>(elem->self()));
  576. }
  577. }
  578. List<Ref<CSharpScript> > to_reload;
  579. // We need to keep reference instances alive during reloading
  580. List<Ref<Reference> > ref_instances;
  581. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  582. CSharpScriptBinding &script_binding = E->value();
  583. Reference *ref = Object::cast_to<Reference>(script_binding.owner);
  584. if (ref) {
  585. ref_instances.push_back(Ref<Reference>(ref));
  586. }
  587. }
  588. // As scripts are going to be reloaded, must proceed without locking here
  589. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  590. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  591. Ref<CSharpScript> &script = E->get();
  592. to_reload.push_back(script);
  593. if (script->get_path().empty()) {
  594. script->tied_class_name_for_reload = script->script_class->get_name();
  595. script->tied_class_namespace_for_reload = script->script_class->get_namespace();
  596. }
  597. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  598. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  599. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  600. Object *obj = F->get();
  601. script->pending_reload_instances.insert(obj->get_instance_id());
  602. Reference *ref = Object::cast_to<Reference>(obj);
  603. if (ref) {
  604. ref_instances.push_back(Ref<Reference>(ref));
  605. }
  606. }
  607. #ifdef TOOLS_ENABLED
  608. for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) {
  609. Object *obj = F->get()->get_owner();
  610. script->pending_reload_instances.insert(obj->get_instance_id());
  611. Reference *ref = Object::cast_to<Reference>(obj);
  612. if (ref) {
  613. ref_instances.push_back(Ref<Reference>(ref));
  614. }
  615. }
  616. #endif
  617. // Save state and remove script from instances
  618. Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
  619. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  620. Object *obj = F->get();
  621. ERR_CONTINUE(!obj->get_script_instance());
  622. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  623. // Call OnBeforeSerialize
  624. if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  625. obj->get_script_instance()->call_multilevel(string_names.on_before_serialize);
  626. // Save instance info
  627. CSharpScript::StateBackup state;
  628. // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
  629. csi->get_properties_state_for_reloading(state.properties);
  630. owners_map[obj->get_instance_id()] = state;
  631. }
  632. }
  633. // After the state of all instances is saved, clear scripts and script instances
  634. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  635. Ref<CSharpScript> &script = E->get();
  636. while (script->instances.front()) {
  637. Object *obj = script->instances.front()->get();
  638. obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  639. }
  640. script->_clear();
  641. }
  642. // Do domain reload
  643. if (gdmono->reload_scripts_domain() != OK) {
  644. // Failed to reload the scripts domain
  645. // Make sure to add the scripts back to their owners before returning
  646. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  647. Ref<CSharpScript> scr = E->get();
  648. for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
  649. Object *obj = ObjectDB::get_instance(F->key());
  650. if (!obj)
  651. continue;
  652. ObjectID obj_id = obj->get_instance_id();
  653. // Use a placeholder for now to avoid losing the state when saving a scene
  654. obj->set_script(scr.get_ref_ptr());
  655. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  656. obj->set_script_instance(placeholder);
  657. #ifdef TOOLS_ENABLED
  658. // Even though build didn't fail, this tells the placeholder to keep properties and
  659. // it allows using property_set_fallback for restoring the state without a valid script.
  660. scr->placeholder_fallback_enabled = true;
  661. #endif
  662. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  663. for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
  664. placeholder->property_set_fallback(G->get().first, G->get().second, NULL);
  665. }
  666. scr->pending_reload_state.erase(obj_id);
  667. }
  668. }
  669. return;
  670. }
  671. List<Ref<CSharpScript> > to_reload_state;
  672. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  673. Ref<CSharpScript> script = E->get();
  674. if (!script->get_path().empty()) {
  675. #ifdef TOOLS_ENABLED
  676. script->exports_invalidated = true;
  677. #endif
  678. script->signals_invalidated = true;
  679. script->reload(p_soft_reload);
  680. script->update_exports();
  681. } else {
  682. const StringName &class_namespace = script->tied_class_namespace_for_reload;
  683. const StringName &class_name = script->tied_class_name_for_reload;
  684. GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
  685. GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
  686. // Search in project and tools assemblies first as those are the most likely to have the class
  687. GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : NULL);
  688. if (!script_class) {
  689. script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : NULL);
  690. }
  691. if (!script_class) {
  692. script_class = gdmono->get_class(class_namespace, class_name);
  693. }
  694. if (!script_class) {
  695. // The class was removed, can't reload
  696. script->pending_reload_instances.clear();
  697. continue;
  698. }
  699. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
  700. if (!obj_type) {
  701. // The class no longer inherits Godot.Object, can't reload
  702. script->pending_reload_instances.clear();
  703. continue;
  704. }
  705. GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
  706. Ref<CSharpScript> new_script = CSharpScript::create_for_managed_type(script_class, native);
  707. CRASH_COND(new_script.is_null());
  708. new_script->pending_reload_instances = script->pending_reload_instances;
  709. new_script->pending_reload_state = script->pending_reload_state;
  710. script = new_script;
  711. }
  712. String native_name = NATIVE_GDMONOCLASS_NAME(script->native);
  713. {
  714. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  715. ObjectID obj_id = F->get();
  716. Object *obj = ObjectDB::get_instance(obj_id);
  717. if (!obj) {
  718. script->pending_reload_state.erase(obj_id);
  719. continue;
  720. }
  721. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  722. // No longer inherits the same compatible type, can't reload
  723. script->pending_reload_state.erase(obj_id);
  724. continue;
  725. }
  726. ScriptInstance *si = obj->get_script_instance();
  727. #ifdef TOOLS_ENABLED
  728. if (si) {
  729. // If the script instance is not null, then it must be a placeholder.
  730. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  731. CRASH_COND(!si->is_placeholder());
  732. if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
  733. // Replace placeholder with a script instance
  734. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  735. // Backup placeholder script instance state before replacing it with a script instance
  736. si->get_property_state(state_backup.properties);
  737. ScriptInstance *script_instance = script->instance_create(obj);
  738. if (script_instance) {
  739. script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  740. obj->set_script_instance(script_instance);
  741. }
  742. }
  743. continue;
  744. }
  745. #else
  746. CRASH_COND(si != NULL);
  747. #endif
  748. // Re-create script instance
  749. obj->set_script(script.get_ref_ptr()); // will create the script instance as well
  750. }
  751. }
  752. to_reload_state.push_back(script);
  753. }
  754. for (List<Ref<CSharpScript> >::Element *E = to_reload_state.front(); E; E = E->next()) {
  755. Ref<CSharpScript> script = E->get();
  756. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  757. ObjectID obj_id = F->get();
  758. Object *obj = ObjectDB::get_instance(obj_id);
  759. if (!obj) {
  760. script->pending_reload_state.erase(obj_id);
  761. continue;
  762. }
  763. ERR_CONTINUE(!obj->get_script_instance());
  764. // TODO: Restore serialized state
  765. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  766. for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
  767. obj->get_script_instance()->set(G->get().first, G->get().second);
  768. }
  769. // Call OnAfterDeserialization
  770. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  771. if (csi && csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  772. obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
  773. }
  774. script->pending_reload_instances.clear();
  775. }
  776. #ifdef TOOLS_ENABLED
  777. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  778. if (Engine::get_singleton()->is_editor_hint()) {
  779. EditorNode::get_singleton()->get_inspector()->update_tree();
  780. NodeDock::singleton->update_lists();
  781. }
  782. #endif
  783. }
  784. #endif
  785. void CSharpLanguage::_load_scripts_metadata() {
  786. scripts_metadata.clear();
  787. String scripts_metadata_filename = "scripts_metadata.";
  788. #ifdef TOOLS_ENABLED
  789. scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player";
  790. #else
  791. #ifdef DEBUG_ENABLED
  792. scripts_metadata_filename += "debug";
  793. #else
  794. scripts_metadata_filename += "release";
  795. #endif
  796. #endif
  797. String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename);
  798. if (FileAccess::exists(scripts_metadata_path)) {
  799. String old_json;
  800. Error ferr = read_all_file_utf8(scripts_metadata_path, old_json);
  801. ERR_FAIL_COND(ferr != OK);
  802. Variant old_dict_var;
  803. String err_str;
  804. int err_line;
  805. Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line);
  806. if (json_err != OK) {
  807. ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ")");
  808. return;
  809. }
  810. scripts_metadata = old_dict_var.operator Dictionary();
  811. scripts_metadata_invalidated = false;
  812. print_verbose("Successfully loaded scripts metadata");
  813. } else {
  814. if (!Engine::get_singleton()->is_editor_hint()) {
  815. ERR_PRINT("Missing scripts metadata file");
  816. }
  817. }
  818. }
  819. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  820. p_extensions->push_back("cs");
  821. }
  822. #ifdef TOOLS_ENABLED
  823. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  824. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  825. }
  826. bool CSharpLanguage::overrides_external_editor() {
  827. return get_godotsharp_editor()->call("OverridesExternalEditor");
  828. }
  829. #endif
  830. void CSharpLanguage::thread_enter() {
  831. #if 0
  832. if (mono->is_runtime_initialized()) {
  833. GDMonoUtils::attach_current_thread();
  834. }
  835. #endif
  836. }
  837. void CSharpLanguage::thread_exit() {
  838. #if 0
  839. if (mono->is_runtime_initialized()) {
  840. GDMonoUtils::detach_current_thread();
  841. }
  842. #endif
  843. }
  844. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  845. // Not a parser error in our case, but it's still used for other type of errors
  846. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  847. _debug_parse_err_line = p_line;
  848. _debug_parse_err_file = p_file;
  849. _debug_error = p_error;
  850. ScriptDebugger::get_singleton()->debug(this, false);
  851. return true;
  852. } else {
  853. return false;
  854. }
  855. }
  856. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  857. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  858. _debug_parse_err_line = -1;
  859. _debug_parse_err_file = "";
  860. _debug_error = p_error;
  861. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  862. return true;
  863. } else {
  864. return false;
  865. }
  866. }
  867. void CSharpLanguage::_on_scripts_domain_unloaded() {
  868. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  869. CSharpScriptBinding &script_binding = E->value();
  870. script_binding.inited = false;
  871. }
  872. scripts_metadata_invalidated = true;
  873. }
  874. #ifdef TOOLS_ENABLED
  875. void CSharpLanguage::_editor_init_callback() {
  876. register_editor_internal_calls();
  877. // Initialize GodotSharpEditor
  878. GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
  879. CRASH_COND(editor_klass == NULL);
  880. MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
  881. CRASH_COND(mono_object == NULL);
  882. MonoException *exc = NULL;
  883. GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
  884. UNHANDLED_EXCEPTION(exc);
  885. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object));
  886. CRASH_COND(godotsharp_editor == NULL);
  887. // Enable it as a plugin
  888. EditorNode::add_editor_plugin(godotsharp_editor);
  889. godotsharp_editor->enable_plugin();
  890. get_singleton()->godotsharp_editor = godotsharp_editor;
  891. }
  892. #endif
  893. void CSharpLanguage::set_language_index(int p_idx) {
  894. ERR_FAIL_COND(lang_idx != -1);
  895. lang_idx = p_idx;
  896. }
  897. void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) {
  898. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  899. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  900. p_gchandle->release();
  901. }
  902. }
  903. void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle) {
  904. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_expected_obj); // We might lock after this, so pin it
  905. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  906. SCOPED_MUTEX_LOCK(get_singleton()->script_gchandle_release_mutex);
  907. MonoObject *target = p_gchandle->get_target();
  908. // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
  909. // already released and could have been replaced) or if we can't get its target MonoObject*
  910. // (which doesn't necessarily mean it was released, and we want it released in order to
  911. // avoid locking other threads unnecessarily).
  912. if (target == p_expected_obj || target == NULL) {
  913. p_gchandle->release();
  914. }
  915. }
  916. MonoGCHandle::free_handle(pinned_gchandle);
  917. }
  918. CSharpLanguage::CSharpLanguage() {
  919. ERR_FAIL_COND(singleton);
  920. singleton = this;
  921. finalizing = false;
  922. gdmono = NULL;
  923. #ifdef NO_THREADS
  924. script_instances_mutex = NULL;
  925. script_gchandle_release_mutex = NULL;
  926. language_bind_mutex = NULL;
  927. #else
  928. script_instances_mutex = Mutex::create();
  929. script_gchandle_release_mutex = Mutex::create();
  930. language_bind_mutex = Mutex::create();
  931. #endif
  932. lang_idx = -1;
  933. scripts_metadata_invalidated = true;
  934. godotsharp_editor = NULL;
  935. }
  936. CSharpLanguage::~CSharpLanguage() {
  937. finish();
  938. if (script_instances_mutex) {
  939. memdelete(script_instances_mutex);
  940. script_instances_mutex = NULL;
  941. }
  942. if (language_bind_mutex) {
  943. memdelete(language_bind_mutex);
  944. language_bind_mutex = NULL;
  945. }
  946. if (script_gchandle_release_mutex) {
  947. memdelete(script_gchandle_release_mutex);
  948. script_gchandle_release_mutex = NULL;
  949. }
  950. singleton = NULL;
  951. }
  952. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  953. #ifdef DEBUG_ENABLED
  954. // I don't trust you
  955. if (p_object->get_script_instance()) {
  956. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  957. CRASH_COND(csharp_instance != NULL && !csharp_instance->is_destructing_script_instance());
  958. }
  959. #endif
  960. StringName type_name = p_object->get_class_name();
  961. // ¯\_(ツ)_/¯
  962. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  963. while (classinfo && !classinfo->exposed)
  964. classinfo = classinfo->inherits_ptr;
  965. ERR_FAIL_NULL_V(classinfo, false);
  966. type_name = classinfo->name;
  967. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  968. ERR_FAIL_NULL_V(type_class, false);
  969. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  970. ERR_FAIL_NULL_V(mono_object, false);
  971. r_script_binding.inited = true;
  972. r_script_binding.type_name = type_name;
  973. r_script_binding.wrapper_class = type_class; // cache
  974. r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
  975. r_script_binding.owner = p_object;
  976. // Tie managed to unmanaged
  977. Reference *ref = Object::cast_to<Reference>(p_object);
  978. if (ref) {
  979. // Unsafe refcount increment. The managed instance also counts as a reference.
  980. // This way if the unmanaged world has no references to our owner
  981. // but the managed instance is alive, the refcount will be 1 instead of 0.
  982. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  983. ref->reference();
  984. }
  985. return true;
  986. }
  987. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  988. SCOPED_MUTEX_LOCK(language_bind_mutex);
  989. Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
  990. if (match)
  991. return (void *)match;
  992. CSharpScriptBinding script_binding;
  993. if (!setup_csharp_script_binding(script_binding, p_object))
  994. return NULL;
  995. return (void *)insert_script_binding(p_object, script_binding);
  996. }
  997. Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  998. return script_bindings.insert(p_object, p_script_binding);
  999. }
  1000. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  1001. if (GDMono::get_singleton() == NULL) {
  1002. #ifdef DEBUG_ENABLED
  1003. CRASH_COND(!script_bindings.empty());
  1004. #endif
  1005. // Mono runtime finalized, all the gchandle bindings were already released
  1006. return;
  1007. }
  1008. if (finalizing)
  1009. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1010. {
  1011. SCOPED_MUTEX_LOCK(language_bind_mutex);
  1012. Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;
  1013. CSharpScriptBinding &script_binding = data->value();
  1014. if (script_binding.inited) {
  1015. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1016. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1017. MonoObject *mono_object = script_binding.gchandle->get_target();
  1018. if (mono_object) {
  1019. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  1020. }
  1021. }
  1022. script_bindings.erase(data);
  1023. }
  1024. }
  1025. void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
  1026. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1027. #ifdef DEBUG_ENABLED
  1028. CRASH_COND(!ref_owner);
  1029. #endif
  1030. void *data = p_object->get_script_instance_binding(get_language_index());
  1031. CRASH_COND(!data);
  1032. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1033. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1034. if (!script_binding.inited)
  1035. return;
  1036. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1037. // The reference count was increased after the managed side was the only one referencing our owner.
  1038. // This means the owner is being referenced again by the unmanaged side,
  1039. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1040. MonoObject *target = gchandle->get_target();
  1041. if (!target)
  1042. return; // Called after the managed side was collected, so nothing to do here
  1043. // Release the current weak handle and replace it with a strong handle.
  1044. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target);
  1045. gchandle->release();
  1046. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1047. }
  1048. }
  1049. bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
  1050. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1051. #ifdef DEBUG_ENABLED
  1052. CRASH_COND(!ref_owner);
  1053. #endif
  1054. void *data = p_object->get_script_instance_binding(get_language_index());
  1055. CRASH_COND(!data);
  1056. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1057. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1058. int refcount = ref_owner->reference_get_count();
  1059. if (!script_binding.inited)
  1060. return refcount == 0;
  1061. if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1062. // If owner owner is no longer referenced by the unmanaged side,
  1063. // the managed instance takes responsibility of deleting the owner when GCed.
  1064. MonoObject *target = gchandle->get_target();
  1065. if (!target)
  1066. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1067. // Release the current strong handle and replace it with a weak handle.
  1068. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target);
  1069. gchandle->release();
  1070. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1071. return false;
  1072. }
  1073. return refcount == 0;
  1074. }
  1075. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  1076. CSharpInstance *instance = memnew(CSharpInstance);
  1077. Reference *ref = Object::cast_to<Reference>(p_owner);
  1078. instance->base_ref = ref != NULL;
  1079. instance->script = Ref<CSharpScript>(p_script);
  1080. instance->owner = p_owner;
  1081. instance->gchandle = p_gchandle;
  1082. if (instance->base_ref)
  1083. instance->_reference_owner_unsafe();
  1084. p_script->instances.insert(p_owner);
  1085. return instance;
  1086. }
  1087. MonoObject *CSharpInstance::get_mono_object() const {
  1088. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  1089. return gchandle->get_target();
  1090. }
  1091. Object *CSharpInstance::get_owner() {
  1092. return owner;
  1093. }
  1094. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1095. ERR_FAIL_COND_V(!script.is_valid(), false);
  1096. MonoObject *mono_object = get_mono_object();
  1097. ERR_FAIL_NULL_V(mono_object, false);
  1098. GDMonoClass *top = script->script_class;
  1099. while (top && top != script->native) {
  1100. GDMonoField *field = top->get_field(p_name);
  1101. if (field) {
  1102. field->set_value_from_variant(mono_object, p_value);
  1103. return true;
  1104. }
  1105. GDMonoProperty *property = top->get_property(p_name);
  1106. if (property) {
  1107. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
  1108. return true;
  1109. }
  1110. top = top->get_parent_class();
  1111. }
  1112. // Call _set
  1113. top = script->script_class;
  1114. while (top && top != script->native) {
  1115. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  1116. if (method) {
  1117. Variant name = p_name;
  1118. const Variant *args[2] = { &name, &p_value };
  1119. MonoObject *ret = method->invoke(mono_object, args);
  1120. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
  1121. return true;
  1122. break;
  1123. }
  1124. top = top->get_parent_class();
  1125. }
  1126. return false;
  1127. }
  1128. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1129. ERR_FAIL_COND_V(!script.is_valid(), false);
  1130. MonoObject *mono_object = get_mono_object();
  1131. ERR_FAIL_NULL_V(mono_object, false);
  1132. GDMonoClass *top = script->script_class;
  1133. while (top && top != script->native) {
  1134. GDMonoField *field = top->get_field(p_name);
  1135. if (field) {
  1136. MonoObject *value = field->get_value(mono_object);
  1137. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1138. return true;
  1139. }
  1140. GDMonoProperty *property = top->get_property(p_name);
  1141. if (property) {
  1142. MonoException *exc = NULL;
  1143. MonoObject *value = property->get_value(mono_object, &exc);
  1144. if (exc) {
  1145. r_ret = Variant();
  1146. GDMonoUtils::set_pending_exception(exc);
  1147. } else {
  1148. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1149. }
  1150. return true;
  1151. }
  1152. top = top->get_parent_class();
  1153. }
  1154. // Call _get
  1155. top = script->script_class;
  1156. while (top && top != script->native) {
  1157. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  1158. if (method) {
  1159. Variant name = p_name;
  1160. const Variant *args[1] = { &name };
  1161. MonoObject *ret = method->invoke(mono_object, args);
  1162. if (ret) {
  1163. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  1164. return true;
  1165. }
  1166. break;
  1167. }
  1168. top = top->get_parent_class();
  1169. }
  1170. return false;
  1171. }
  1172. void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state) {
  1173. List<PropertyInfo> pinfo;
  1174. get_property_list(&pinfo);
  1175. for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
  1176. Pair<StringName, Variant> state_pair;
  1177. state_pair.first = E->get().name;
  1178. ManagedType managedType;
  1179. GDMonoField *field = script->script_class->get_field(state_pair.first);
  1180. if (!field)
  1181. continue; // Properties ignored. We get the property baking fields instead.
  1182. managedType = field->get_type();
  1183. if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
  1184. if (get(state_pair.first, state_pair.second)) {
  1185. r_state.push_back(state_pair);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1191. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  1192. p_properties->push_back(E->value());
  1193. }
  1194. // Call _get_property_list
  1195. ERR_FAIL_COND(!script.is_valid());
  1196. MonoObject *mono_object = get_mono_object();
  1197. ERR_FAIL_NULL(mono_object);
  1198. GDMonoClass *top = script->script_class;
  1199. while (top && top != script->native) {
  1200. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);
  1201. if (method) {
  1202. MonoObject *ret = method->invoke(mono_object);
  1203. if (ret) {
  1204. Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
  1205. for (int i = 0, size = array.size(); i < size; i++)
  1206. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1207. return;
  1208. }
  1209. break;
  1210. }
  1211. top = top->get_parent_class();
  1212. }
  1213. }
  1214. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1215. if (script->member_info.has(p_name)) {
  1216. if (r_is_valid)
  1217. *r_is_valid = true;
  1218. return script->member_info[p_name].type;
  1219. }
  1220. if (r_is_valid)
  1221. *r_is_valid = false;
  1222. return Variant::NIL;
  1223. }
  1224. bool CSharpInstance::has_method(const StringName &p_method) const {
  1225. if (!script.is_valid())
  1226. return false;
  1227. GDMonoClass *top = script->script_class;
  1228. while (top && top != script->native) {
  1229. if (top->has_fetched_method_unknown_params(p_method)) {
  1230. return true;
  1231. }
  1232. top = top->get_parent_class();
  1233. }
  1234. return false;
  1235. }
  1236. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1237. MonoObject *mono_object = get_mono_object();
  1238. if (!mono_object) {
  1239. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1240. ERR_FAIL_V(Variant());
  1241. }
  1242. if (!script.is_valid())
  1243. ERR_FAIL_V(Variant());
  1244. GDMonoClass *top = script->script_class;
  1245. while (top && top != script->native) {
  1246. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1247. if (method) {
  1248. MonoObject *return_value = method->invoke(mono_object, p_args);
  1249. r_error.error = Variant::CallError::CALL_OK;
  1250. if (return_value) {
  1251. return GDMonoMarshal::mono_object_to_variant(return_value);
  1252. } else {
  1253. return Variant();
  1254. }
  1255. }
  1256. top = top->get_parent_class();
  1257. }
  1258. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1259. return Variant();
  1260. }
  1261. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1262. if (script.is_valid()) {
  1263. MonoObject *mono_object = get_mono_object();
  1264. ERR_FAIL_NULL(mono_object);
  1265. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  1266. }
  1267. }
  1268. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  1269. GDMonoClass *top = script->script_class;
  1270. while (top && top != script->native) {
  1271. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1272. if (method) {
  1273. method->invoke(p_mono_object, p_args);
  1274. return;
  1275. }
  1276. top = top->get_parent_class();
  1277. }
  1278. }
  1279. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1280. // Sorry, the method is the one that controls the call order
  1281. call_multilevel(p_method, p_args, p_argcount);
  1282. }
  1283. bool CSharpInstance::_reference_owner_unsafe() {
  1284. #ifdef DEBUG_ENABLED
  1285. CRASH_COND(!base_ref);
  1286. CRASH_COND(owner == NULL);
  1287. CRASH_COND(unsafe_referenced); // already referenced
  1288. #endif
  1289. // Unsafe refcount increment. The managed instance also counts as a reference.
  1290. // This way if the unmanaged world has no references to our owner
  1291. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1292. // See: _unreference_owner_unsafe()
  1293. // May not me referenced yet, so we must use init_ref() instead of reference()
  1294. bool success = Object::cast_to<Reference>(owner)->init_ref();
  1295. unsafe_referenced = success;
  1296. return success;
  1297. }
  1298. bool CSharpInstance::_unreference_owner_unsafe() {
  1299. #ifdef DEBUG_ENABLED
  1300. CRASH_COND(!base_ref);
  1301. CRASH_COND(owner == NULL);
  1302. #endif
  1303. if (!unsafe_referenced)
  1304. return false; // Already unreferenced
  1305. unsafe_referenced = false;
  1306. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1307. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1308. // See: _reference_owner_unsafe()
  1309. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1310. return static_cast<Reference *>(owner)->unreference();
  1311. }
  1312. MonoObject *CSharpInstance::_internal_new_managed() {
  1313. #ifdef DEBUG_ENABLED
  1314. CRASH_COND(!gchandle.is_valid());
  1315. #endif
  1316. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  1317. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1318. if (ctor == NULL) {
  1319. ERR_PRINTS("Cannot create script instance because the class does not define a parameterless constructor: " + script->get_path());
  1320. ERR_EXPLAIN("Constructor not found");
  1321. ERR_FAIL_V(NULL);
  1322. }
  1323. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1324. ERR_FAIL_NULL_V(owner, NULL);
  1325. ERR_FAIL_COND_V(script.is_null(), NULL);
  1326. MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());
  1327. if (!mono_object) {
  1328. // Important to clear this before destroying the script instance here
  1329. script = Ref<CSharpScript>();
  1330. bool die = _unreference_owner_unsafe();
  1331. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  1332. CRASH_COND(die == true);
  1333. owner = NULL;
  1334. ERR_EXPLAIN("Failed to allocate memory for the object");
  1335. ERR_FAIL_V(NULL);
  1336. }
  1337. // Tie managed to unmanaged
  1338. gchandle = MonoGCHandle::create_strong(mono_object);
  1339. if (base_ref)
  1340. _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1341. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
  1342. // Construct
  1343. ctor->invoke_raw(mono_object, NULL);
  1344. return mono_object;
  1345. }
  1346. void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
  1347. #ifdef DEBUG_ENABLED
  1348. CRASH_COND(base_ref);
  1349. CRASH_COND(gchandle.is_null());
  1350. #endif
  1351. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1352. }
  1353. void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1354. #ifdef DEBUG_ENABLED
  1355. CRASH_COND(!base_ref);
  1356. CRASH_COND(gchandle.is_null());
  1357. #endif
  1358. r_remove_script_instance = false;
  1359. if (_unreference_owner_unsafe()) {
  1360. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1361. r_delete_owner = true;
  1362. } else {
  1363. r_delete_owner = false;
  1364. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1365. if (!p_is_finalizer) {
  1366. // If the native instance is still alive and Dispose() was called
  1367. // (instead of the finalizer), then we remove the script instance.
  1368. r_remove_script_instance = true;
  1369. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1370. // If the native instance is still alive and this is called from the finalizer,
  1371. // then it was referenced from another thread before the finalizer could
  1372. // unreference and delete it, so we want to keep it.
  1373. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1374. // could have already been collected. Instead we will create a new managed instance here.
  1375. MonoObject *new_managed = _internal_new_managed();
  1376. if (!new_managed) {
  1377. r_remove_script_instance = true;
  1378. }
  1379. }
  1380. }
  1381. }
  1382. void CSharpInstance::refcount_incremented() {
  1383. #ifdef DEBUG_ENABLED
  1384. CRASH_COND(!base_ref);
  1385. CRASH_COND(owner == NULL);
  1386. #endif
  1387. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1388. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1389. // The reference count was increased after the managed side was the only one referencing our owner.
  1390. // This means the owner is being referenced again by the unmanaged side,
  1391. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1392. // Release the current weak handle and replace it with a strong handle.
  1393. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target());
  1394. gchandle->release();
  1395. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1396. }
  1397. }
  1398. bool CSharpInstance::refcount_decremented() {
  1399. #ifdef DEBUG_ENABLED
  1400. CRASH_COND(!base_ref);
  1401. CRASH_COND(owner == NULL);
  1402. #endif
  1403. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1404. int refcount = ref_owner->reference_get_count();
  1405. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1406. // If owner owner is no longer referenced by the unmanaged side,
  1407. // the managed instance takes responsibility of deleting the owner when GCed.
  1408. // Release the current strong handle and replace it with a weak handle.
  1409. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target());
  1410. gchandle->release();
  1411. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1412. return false;
  1413. }
  1414. ref_dying = (refcount == 0);
  1415. return ref_dying;
  1416. }
  1417. MultiplayerAPI::RPCMode CSharpInstance::_member_get_rpc_mode(IMonoClassMember *p_member) const {
  1418. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  1419. return MultiplayerAPI::RPC_MODE_REMOTE;
  1420. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  1421. return MultiplayerAPI::RPC_MODE_MASTER;
  1422. if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
  1423. return MultiplayerAPI::RPC_MODE_PUPPET;
  1424. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  1425. return MultiplayerAPI::RPC_MODE_PUPPET;
  1426. if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
  1427. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1428. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  1429. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1430. if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
  1431. return MultiplayerAPI::RPC_MODE_MASTERSYNC;
  1432. if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
  1433. return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
  1434. return MultiplayerAPI::RPC_MODE_DISABLED;
  1435. }
  1436. MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  1437. GDMonoClass *top = script->script_class;
  1438. while (top && top != script->native) {
  1439. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  1440. if (method && !method->is_static())
  1441. return _member_get_rpc_mode(method);
  1442. top = top->get_parent_class();
  1443. }
  1444. return MultiplayerAPI::RPC_MODE_DISABLED;
  1445. }
  1446. MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  1447. GDMonoClass *top = script->script_class;
  1448. while (top && top != script->native) {
  1449. GDMonoField *field = top->get_field(p_variable);
  1450. if (field && !field->is_static())
  1451. return _member_get_rpc_mode(field);
  1452. GDMonoProperty *property = top->get_property(p_variable);
  1453. if (property && !property->is_static())
  1454. return _member_get_rpc_mode(property);
  1455. top = top->get_parent_class();
  1456. }
  1457. return MultiplayerAPI::RPC_MODE_DISABLED;
  1458. }
  1459. void CSharpInstance::notification(int p_notification) {
  1460. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1461. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1462. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1463. // to be sent at least once, which happens right before the call to the destructor.
  1464. predelete_notified = true;
  1465. if (base_ref) {
  1466. // It's not safe to proceed if the owner derives Reference and the refcount reached 0.
  1467. // At this point, Dispose() was already called (manually or from the finalizer) so
  1468. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1469. // managed side references it and Dispose() needs to be called to release it.
  1470. // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
  1471. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1472. return;
  1473. }
  1474. _call_notification(p_notification);
  1475. MonoObject *mono_object = get_mono_object();
  1476. ERR_FAIL_NULL(mono_object);
  1477. MonoException *exc = NULL;
  1478. GDMonoUtils::dispose(mono_object, &exc);
  1479. if (exc) {
  1480. GDMonoUtils::set_pending_exception(exc);
  1481. }
  1482. return;
  1483. }
  1484. _call_notification(p_notification);
  1485. }
  1486. void CSharpInstance::_call_notification(int p_notification) {
  1487. MonoObject *mono_object = get_mono_object();
  1488. ERR_FAIL_NULL(mono_object);
  1489. // Custom version of _call_multilevel, optimized for _notification
  1490. uint32_t arg = p_notification;
  1491. void *args[1] = { &arg };
  1492. StringName method_name = CACHED_STRING_NAME(_notification);
  1493. GDMonoClass *top = script->script_class;
  1494. while (top && top != script->native) {
  1495. GDMonoMethod *method = top->get_method(method_name, 1);
  1496. if (method) {
  1497. method->invoke_raw(mono_object, args);
  1498. return;
  1499. }
  1500. top = top->get_parent_class();
  1501. }
  1502. }
  1503. String CSharpInstance::to_string(bool *r_valid) {
  1504. MonoObject *mono_object = get_mono_object();
  1505. if (mono_object == NULL) {
  1506. if (r_valid)
  1507. *r_valid = false;
  1508. return String();
  1509. }
  1510. MonoException *exc = NULL;
  1511. MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc);
  1512. if (exc) {
  1513. GDMonoUtils::set_pending_exception(exc);
  1514. if (r_valid)
  1515. *r_valid = false;
  1516. return String();
  1517. }
  1518. if (result == NULL) {
  1519. if (r_valid)
  1520. *r_valid = false;
  1521. return String();
  1522. }
  1523. return GDMonoMarshal::mono_string_to_godot(result);
  1524. }
  1525. Ref<Script> CSharpInstance::get_script() const {
  1526. return script;
  1527. }
  1528. ScriptLanguage *CSharpInstance::get_language() {
  1529. return CSharpLanguage::get_singleton();
  1530. }
  1531. CSharpInstance::CSharpInstance() :
  1532. owner(NULL),
  1533. base_ref(false),
  1534. ref_dying(false),
  1535. unsafe_referenced(false),
  1536. predelete_notified(false),
  1537. destructing_script_instance(false) {
  1538. }
  1539. CSharpInstance::~CSharpInstance() {
  1540. destructing_script_instance = true;
  1541. if (gchandle.is_valid()) {
  1542. if (!predelete_notified && !ref_dying) {
  1543. // This destructor is not called from the owners destructor.
  1544. // This could be being called from the owner's set_script_instance method,
  1545. // meaning this script is being replaced with another one. If this is the case,
  1546. // we must call Dispose here, because Dispose calls owner->set_script_instance(NULL)
  1547. // and that would mess up with the new script instance if called later.
  1548. MonoObject *mono_object = gchandle->get_target();
  1549. if (mono_object) {
  1550. MonoException *exc = NULL;
  1551. GDMonoUtils::dispose(mono_object, &exc);
  1552. if (exc) {
  1553. GDMonoUtils::set_pending_exception(exc);
  1554. }
  1555. }
  1556. }
  1557. gchandle->release(); // Make sure the gchandle is released
  1558. }
  1559. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1560. if (base_ref && !ref_dying && owner && unsafe_referenced) {
  1561. // The owner's script or script instance is being replaced (or removed)
  1562. // Transfer ownership to an "instance binding"
  1563. void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  1564. CRASH_COND(data == NULL);
  1565. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1566. if (!script_binding.inited) {
  1567. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1568. if (!script_binding.inited) { // Other thread may have set it up
  1569. // Already had a binding that needs to be setup
  1570. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner);
  1571. CRASH_COND(!script_binding.inited);
  1572. }
  1573. }
  1574. bool die = _unreference_owner_unsafe();
  1575. CRASH_COND(die == true); // The "instance binding" should be holding a reference
  1576. }
  1577. if (script.is_valid() && owner) {
  1578. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  1579. #ifdef DEBUG_ENABLED
  1580. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1581. Set<Object *>::Element *match = script->instances.find(owner);
  1582. CRASH_COND(!match);
  1583. script->instances.erase(match);
  1584. #else
  1585. script->instances.erase(owner);
  1586. #endif
  1587. }
  1588. }
  1589. #ifdef TOOLS_ENABLED
  1590. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1591. placeholders.erase(p_placeholder);
  1592. }
  1593. #endif
  1594. #ifdef TOOLS_ENABLED
  1595. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1596. if (base_cache.is_valid()) {
  1597. base_cache->_update_exports_values(values, propnames);
  1598. }
  1599. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1600. values[E->key()] = E->get();
  1601. }
  1602. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1603. propnames.push_back(E->get());
  1604. }
  1605. }
  1606. #endif
  1607. void CSharpScript::_update_member_info_no_exports() {
  1608. if (exports_invalidated) {
  1609. exports_invalidated = false;
  1610. member_info.clear();
  1611. GDMonoClass *top = script_class;
  1612. while (top && top != native) {
  1613. PropertyInfo prop_info;
  1614. bool exported;
  1615. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1616. for (int i = fields.size() - 1; i >= 0; i--) {
  1617. GDMonoField *field = fields[i];
  1618. if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
  1619. StringName member_name = field->get_name();
  1620. member_info[member_name] = prop_info;
  1621. exported_members_cache.push_front(prop_info);
  1622. exported_members_defval_cache[member_name] = Variant();
  1623. }
  1624. }
  1625. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1626. for (int i = properties.size() - 1; i >= 0; i--) {
  1627. GDMonoProperty *property = properties[i];
  1628. if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
  1629. StringName member_name = property->get_name();
  1630. member_info[member_name] = prop_info;
  1631. exported_members_cache.push_front(prop_info);
  1632. exported_members_defval_cache[member_name] = Variant();
  1633. }
  1634. }
  1635. top = top->get_parent_class();
  1636. }
  1637. }
  1638. }
  1639. bool CSharpScript::_update_exports() {
  1640. #ifdef TOOLS_ENABLED
  1641. if (!Engine::get_singleton()->is_editor_hint())
  1642. return false;
  1643. placeholder_fallback_enabled = true; // until proven otherwise
  1644. if (!valid)
  1645. return false;
  1646. bool changed = false;
  1647. if (exports_invalidated) {
  1648. exports_invalidated = false;
  1649. changed = true;
  1650. member_info.clear();
  1651. exported_members_cache.clear();
  1652. exported_members_defval_cache.clear();
  1653. // Here we create a temporary managed instance of the class to get the initial values
  1654. MonoObject *tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  1655. if (!tmp_object) {
  1656. ERR_PRINT("Failed to allocate temporary MonoObject");
  1657. return false;
  1658. }
  1659. uint32_t tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed)
  1660. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1661. if (ctor == NULL) {
  1662. ERR_PRINTS("Cannot construct temporary MonoObject because the class does not define a parameterless constructor: " + get_path());
  1663. ERR_EXPLAIN("Constructor not found");
  1664. ERR_FAIL_V(NULL);
  1665. }
  1666. MonoException *ctor_exc = NULL;
  1667. ctor->invoke(tmp_object, NULL, &ctor_exc);
  1668. if (ctor_exc) {
  1669. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1670. tmp_object = NULL;
  1671. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1672. GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
  1673. return false;
  1674. }
  1675. GDMonoClass *top = script_class;
  1676. while (top && top != native) {
  1677. PropertyInfo prop_info;
  1678. bool exported;
  1679. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1680. for (int i = fields.size() - 1; i >= 0; i--) {
  1681. GDMonoField *field = fields[i];
  1682. if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
  1683. StringName member_name = field->get_name();
  1684. if (exported) {
  1685. member_info[member_name] = prop_info;
  1686. exported_members_cache.push_front(prop_info);
  1687. if (tmp_object) {
  1688. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1689. }
  1690. } else {
  1691. member_info[member_name] = prop_info;
  1692. }
  1693. }
  1694. }
  1695. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1696. for (int i = properties.size() - 1; i >= 0; i--) {
  1697. GDMonoProperty *property = properties[i];
  1698. if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
  1699. StringName member_name = property->get_name();
  1700. if (exported) {
  1701. member_info[member_name] = prop_info;
  1702. exported_members_cache.push_front(prop_info);
  1703. if (tmp_object) {
  1704. MonoException *exc = NULL;
  1705. MonoObject *ret = property->get_value(tmp_object, &exc);
  1706. if (exc) {
  1707. exported_members_defval_cache[member_name] = Variant();
  1708. GDMonoUtils::debug_print_unhandled_exception(exc);
  1709. } else {
  1710. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
  1711. }
  1712. }
  1713. } else {
  1714. member_info[member_name] = prop_info;
  1715. }
  1716. }
  1717. }
  1718. top = top->get_parent_class();
  1719. }
  1720. // Dispose the temporary managed instance
  1721. MonoException *exc = NULL;
  1722. GDMonoUtils::dispose(tmp_object, &exc);
  1723. if (exc) {
  1724. ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
  1725. GDMonoUtils::debug_print_unhandled_exception(exc);
  1726. }
  1727. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1728. tmp_object = NULL;
  1729. }
  1730. placeholder_fallback_enabled = false;
  1731. if (placeholders.size()) {
  1732. // Update placeholders if any
  1733. Map<StringName, Variant> values;
  1734. List<PropertyInfo> propnames;
  1735. _update_exports_values(values, propnames);
  1736. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1737. E->get()->update(propnames, values);
  1738. }
  1739. }
  1740. return changed;
  1741. #endif
  1742. return false;
  1743. }
  1744. void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
  1745. // no need to load the script's signals more than once
  1746. if (!signals_invalidated) {
  1747. return;
  1748. }
  1749. // make sure this classes signals are empty when loading for the first time
  1750. _signals.clear();
  1751. GDMonoClass *top = p_class;
  1752. while (top && top != p_native_class) {
  1753. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1754. for (int i = delegates.size() - 1; i >= 0; --i) {
  1755. Vector<Argument> parameters;
  1756. GDMonoClass *delegate = delegates[i];
  1757. if (_get_signal(top, delegate, parameters)) {
  1758. _signals[delegate->get_name()] = parameters;
  1759. }
  1760. }
  1761. top = top->get_parent_class();
  1762. }
  1763. signals_invalidated = false;
  1764. }
  1765. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1766. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1767. MonoType *raw_type = p_delegate->get_mono_type();
  1768. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1769. // Arguments are accessibles as arguments of .Invoke method
  1770. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1771. Vector<StringName> names;
  1772. Vector<ManagedType> types;
  1773. invoke->get_parameter_names(names);
  1774. invoke->get_parameter_types(types);
  1775. if (names.size() == types.size()) {
  1776. for (int i = 0; i < names.size(); ++i) {
  1777. Argument arg;
  1778. arg.name = names[i];
  1779. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1780. if (arg.type == Variant::NIL) {
  1781. ERR_PRINTS("Unknown type of signal parameter: " + arg.name + " in " + p_class->get_full_name());
  1782. return false;
  1783. }
  1784. params.push_back(arg);
  1785. }
  1786. return true;
  1787. }
  1788. }
  1789. }
  1790. return false;
  1791. }
  1792. #ifdef TOOLS_ENABLED
  1793. /**
  1794. * Returns false if there was an error, otherwise true.
  1795. * If there was an error, r_prop_info and r_exported are not assigned any value.
  1796. */
  1797. bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
  1798. // Goddammit, C++. All I wanted was some nested functions.
  1799. #define MEMBER_FULL_QUALIFIED_NAME(m_member) \
  1800. (m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())
  1801. if (p_member->is_static()) {
  1802. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1803. ERR_PRINTS("Cannot export member because it is static: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
  1804. return false;
  1805. }
  1806. if (member_info.has(p_member->get_name()))
  1807. return false;
  1808. ManagedType type;
  1809. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
  1810. type = static_cast<GDMonoField *>(p_member)->get_type();
  1811. } else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1812. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1813. } else {
  1814. CRASH_NOW();
  1815. }
  1816. bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));
  1817. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1818. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1819. if (!property->has_getter()) {
  1820. if (exported)
  1821. ERR_PRINTS("Read-only property cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
  1822. return false;
  1823. }
  1824. if (!property->has_setter()) {
  1825. if (exported)
  1826. ERR_PRINTS("Write-only property (without getter) cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
  1827. return false;
  1828. }
  1829. }
  1830. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1831. if (!p_inspect_export || !exported) {
  1832. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1833. r_exported = false;
  1834. return true;
  1835. }
  1836. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1837. PropertyHint hint = PROPERTY_HINT_NONE;
  1838. String hint_string;
  1839. if (variant_type == Variant::NIL) {
  1840. ERR_PRINTS("Unknown exported member type: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
  1841. return false;
  1842. }
  1843. int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);
  1844. if (hint_res == -1) {
  1845. ERR_EXPLAIN("Error while trying to determine information about the exported member: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
  1846. ERR_FAIL_V(false);
  1847. }
  1848. if (hint_res == 0) {
  1849. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1850. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1851. }
  1852. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1853. r_exported = true;
  1854. return true;
  1855. #undef MEMBER_FULL_QUALIFIED_NAME
  1856. }
  1857. int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) {
  1858. if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) {
  1859. r_hint = PROPERTY_HINT_ENUM;
  1860. Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields();
  1861. MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr());
  1862. String name_only_hint_string;
  1863. // True: enum Foo { Bar, Baz, Quux }
  1864. // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
  1865. // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
  1866. bool uses_default_values = true;
  1867. for (int i = 0; i < fields.size(); i++) {
  1868. MonoClassField *field = fields[i];
  1869. if (i > 0) {
  1870. r_hint_string += ",";
  1871. name_only_hint_string += ",";
  1872. }
  1873. String enum_field_name = mono_field_get_name(field);
  1874. r_hint_string += enum_field_name;
  1875. name_only_hint_string += enum_field_name;
  1876. // TODO:
  1877. // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
  1878. // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
  1879. MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL);
  1880. if (val_obj == NULL) {
  1881. ERR_EXPLAIN("Failed to get '" + enum_field_name + "' constant enum value");
  1882. ERR_FAIL_V(-1);
  1883. }
  1884. bool r_error;
  1885. uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
  1886. if (r_error) {
  1887. ERR_EXPLAIN("Failed to unbox '" + enum_field_name + "' constant enum value");
  1888. ERR_FAIL_V(-1);
  1889. }
  1890. if (val != (unsigned int)i) {
  1891. uses_default_values = false;
  1892. }
  1893. r_hint_string += ":";
  1894. r_hint_string += String::num_uint64(val);
  1895. }
  1896. if (uses_default_values) {
  1897. // If we use the format NAME:VAL, that's what the editor displays.
  1898. // That's annoying if the user is not using custom values for the enum constants.
  1899. // This may not be needed in the future if the editor is changed to not display values.
  1900. r_hint_string = name_only_hint_string;
  1901. }
  1902. } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) {
  1903. GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
  1904. CRASH_COND(field_native_class == NULL);
  1905. r_hint = PROPERTY_HINT_RESOURCE_TYPE;
  1906. r_hint_string = NATIVE_GDMONOCLASS_NAME(field_native_class);
  1907. } else if (p_allow_generics && p_variant_type == Variant::ARRAY) {
  1908. // Nested arrays are not supported in the inspector
  1909. ManagedType elem_type;
  1910. if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type))
  1911. return 0;
  1912. Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);
  1913. PropertyHint elem_hint = PROPERTY_HINT_NONE;
  1914. String elem_hint_string;
  1915. if (elem_variant_type == Variant::NIL) {
  1916. ERR_EXPLAIN("Unknown array element type");
  1917. ERR_FAIL_V(-1);
  1918. }
  1919. int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string);
  1920. if (hint_res == -1) {
  1921. ERR_EXPLAIN("Error while trying to determine information about the array element type");
  1922. ERR_FAIL_V(-1);
  1923. }
  1924. // Format: type/hint:hint_string
  1925. r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string;
  1926. r_hint = PROPERTY_HINT_TYPE_STRING;
  1927. } else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) {
  1928. // TODO: Dictionaries are not supported in the inspector
  1929. } else {
  1930. return 0;
  1931. }
  1932. return 1;
  1933. }
  1934. #endif
  1935. void CSharpScript::_clear() {
  1936. tool = false;
  1937. valid = false;
  1938. base = NULL;
  1939. native = NULL;
  1940. script_class = NULL;
  1941. }
  1942. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1943. if (unlikely(GDMono::get_singleton() == NULL)) {
  1944. // Probably not the best error but eh.
  1945. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1946. return Variant();
  1947. }
  1948. GDMonoClass *top = script_class;
  1949. while (top && top != native) {
  1950. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1951. if (method && method->is_static()) {
  1952. MonoObject *result = method->invoke(NULL, p_args);
  1953. if (result) {
  1954. return GDMonoMarshal::mono_object_to_variant(result);
  1955. } else {
  1956. return Variant();
  1957. }
  1958. }
  1959. top = top->get_parent_class();
  1960. }
  1961. // No static method found. Try regular instance calls
  1962. return Script::call(p_method, p_args, p_argcount, r_error);
  1963. }
  1964. void CSharpScript::_resource_path_changed() {
  1965. String path = get_path();
  1966. if (!path.empty()) {
  1967. name = get_path().get_file().get_basename();
  1968. }
  1969. }
  1970. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1971. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1972. r_ret = get_source_code();
  1973. return true;
  1974. }
  1975. return false;
  1976. }
  1977. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1978. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1979. set_source_code(p_value);
  1980. reload();
  1981. return true;
  1982. }
  1983. return false;
  1984. }
  1985. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1986. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  1987. }
  1988. void CSharpScript::_bind_methods() {
  1989. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
  1990. }
  1991. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
  1992. // This method should not fail
  1993. CRASH_COND(p_class == NULL);
  1994. // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
  1995. Ref<CSharpScript> script = memnew(CSharpScript);
  1996. script->name = p_class->get_name();
  1997. script->script_class = p_class;
  1998. script->native = p_native;
  1999. CRASH_COND(script->native == NULL);
  2000. GDMonoClass *base = script->script_class->get_parent_class();
  2001. if (base != script->native)
  2002. script->base = base;
  2003. script->valid = true;
  2004. script->tool = script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2005. if (!script->tool) {
  2006. GDMonoClass *nesting_class = script->script_class->get_nesting_class();
  2007. script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2008. }
  2009. #if TOOLS_ENABLED
  2010. if (!script->tool) {
  2011. script->tool = script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2012. }
  2013. #endif
  2014. #ifdef DEBUG_ENABLED
  2015. // For debug builds, we must fetch from all native base methods as well.
  2016. // Native base methods must be fetched before the current class.
  2017. // Not needed if the script class itself is a native class.
  2018. if (script->script_class != script->native) {
  2019. GDMonoClass *native_top = script->native;
  2020. while (native_top) {
  2021. native_top->fetch_methods_with_godot_api_checks(script->native);
  2022. if (native_top == CACHED_CLASS(GodotObject))
  2023. break;
  2024. native_top = native_top->get_parent_class();
  2025. }
  2026. }
  2027. #endif
  2028. script->script_class->fetch_methods_with_godot_api_checks(script->native);
  2029. // Need to fetch method from base classes as well
  2030. GDMonoClass *top = script->script_class;
  2031. while (top && top != script->native) {
  2032. top->fetch_methods_with_godot_api_checks(script->native);
  2033. top = top->get_parent_class();
  2034. }
  2035. script->load_script_signals(script->script_class, script->native);
  2036. script->_update_member_info_no_exports();
  2037. return script;
  2038. }
  2039. bool CSharpScript::can_instance() const {
  2040. #ifdef TOOLS_ENABLED
  2041. if (Engine::get_singleton()->is_editor_hint()) {
  2042. // Hack to lower the risk of attached scripts not being added to the C# project
  2043. if (!get_path().empty() && get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  2044. if (_create_project_solution_if_needed()) {
  2045. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2046. "Compile",
  2047. ProjectSettings::get_singleton()->globalize_path(get_path()));
  2048. } else {
  2049. ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created.");
  2050. }
  2051. }
  2052. }
  2053. #endif
  2054. #ifdef TOOLS_ENABLED
  2055. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  2056. #else
  2057. bool extra_cond = true;
  2058. #endif
  2059. // FIXME Need to think this through better.
  2060. // For tool scripts, this will never fire if the class is not found. That's because we
  2061. // don't know if it's a tool script if we can't find the class to access the attributes.
  2062. if (extra_cond && !script_class) {
  2063. if (GDMono::get_singleton()->get_project_assembly() == NULL) {
  2064. // The project assembly is not loaded
  2065. ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path());
  2066. ERR_FAIL_V(NULL);
  2067. } else {
  2068. // The project assembly is loaded, but the class could not found
  2069. ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path());
  2070. ERR_FAIL_V(NULL);
  2071. }
  2072. }
  2073. return valid && extra_cond;
  2074. }
  2075. StringName CSharpScript::get_instance_base_type() const {
  2076. if (native)
  2077. return native->get_name();
  2078. else
  2079. return StringName();
  2080. }
  2081. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  2082. /* STEP 1, CREATE */
  2083. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  2084. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  2085. if (ctor == NULL) {
  2086. if (p_argcount == 0) {
  2087. String path = get_path();
  2088. ERR_PRINTS("Cannot create script instance. The class '" + script_class->get_full_name() +
  2089. "' does not define a parameterless constructor." + (path.empty() ? String() : ". Path: " + path));
  2090. }
  2091. ERR_EXPLAIN("Constructor not found");
  2092. ERR_FAIL_V(NULL);
  2093. }
  2094. Ref<Reference> ref;
  2095. if (p_isref) {
  2096. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  2097. ref = Ref<Reference>(static_cast<Reference *>(p_owner));
  2098. }
  2099. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  2100. if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) {
  2101. void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  2102. CRASH_COND(data == NULL);
  2103. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  2104. if (script_binding.inited && script_binding.gchandle.is_valid()) {
  2105. MonoObject *mono_object = script_binding.gchandle->get_target();
  2106. if (mono_object) {
  2107. MonoException *exc = NULL;
  2108. GDMonoUtils::dispose(mono_object, &exc);
  2109. if (exc) {
  2110. GDMonoUtils::set_pending_exception(exc);
  2111. }
  2112. }
  2113. script_binding.inited = false;
  2114. }
  2115. }
  2116. CSharpInstance *instance = memnew(CSharpInstance);
  2117. instance->base_ref = p_isref;
  2118. instance->script = Ref<CSharpScript>(this);
  2119. instance->owner = p_owner;
  2120. instance->owner->set_script_instance(instance);
  2121. /* STEP 2, INITIALIZE AND CONSTRUCT */
  2122. MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  2123. if (!mono_object) {
  2124. // Important to clear this before destroying the script instance here
  2125. instance->script = Ref<CSharpScript>();
  2126. instance->owner = NULL;
  2127. bool die = instance->_unreference_owner_unsafe();
  2128. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  2129. CRASH_COND(die == true);
  2130. p_owner->set_script_instance(NULL);
  2131. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  2132. ERR_EXPLAIN("Failed to allocate memory for the object");
  2133. ERR_FAIL_V(NULL);
  2134. }
  2135. // Tie managed to unmanaged
  2136. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  2137. if (instance->base_ref)
  2138. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  2139. {
  2140. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2141. instances.insert(instance->owner);
  2142. }
  2143. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  2144. // Construct
  2145. ctor->invoke(mono_object, p_args);
  2146. /* STEP 3, PARTY */
  2147. //@TODO make thread safe
  2148. return instance;
  2149. }
  2150. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  2151. if (!valid) {
  2152. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  2153. return Variant();
  2154. }
  2155. r_error.error = Variant::CallError::CALL_OK;
  2156. REF ref;
  2157. Object *owner = NULL;
  2158. ERR_FAIL_NULL_V(native, Variant());
  2159. owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  2160. Reference *r = Object::cast_to<Reference>(owner);
  2161. if (r) {
  2162. ref = REF(r);
  2163. }
  2164. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  2165. if (!instance) {
  2166. if (ref.is_null()) {
  2167. memdelete(owner); //no owner, sorry
  2168. }
  2169. return Variant();
  2170. }
  2171. if (ref.is_valid()) {
  2172. return ref;
  2173. } else {
  2174. return owner;
  2175. }
  2176. }
  2177. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  2178. #ifdef DEBUG_ENABLED
  2179. CRASH_COND(!valid);
  2180. #endif
  2181. if (native) {
  2182. String native_name = NATIVE_GDMONOCLASS_NAME(native);
  2183. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  2184. if (ScriptDebugger::get_singleton()) {
  2185. 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() + "'");
  2186. }
  2187. ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  2188. ERR_FAIL_V(NULL);
  2189. }
  2190. }
  2191. Variant::CallError unchecked_error;
  2192. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error);
  2193. }
  2194. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  2195. #ifdef TOOLS_ENABLED
  2196. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  2197. placeholders.insert(si);
  2198. _update_exports();
  2199. return si;
  2200. #else
  2201. return NULL;
  2202. #endif
  2203. }
  2204. bool CSharpScript::instance_has(const Object *p_this) const {
  2205. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2206. return instances.has((Object *)p_this);
  2207. }
  2208. bool CSharpScript::has_source_code() const {
  2209. return !source.empty();
  2210. }
  2211. String CSharpScript::get_source_code() const {
  2212. return source;
  2213. }
  2214. void CSharpScript::set_source_code(const String &p_code) {
  2215. if (source == p_code)
  2216. return;
  2217. source = p_code;
  2218. #ifdef TOOLS_ENABLED
  2219. source_changed_cache = true;
  2220. #endif
  2221. }
  2222. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  2223. if (!script_class)
  2224. return;
  2225. // TODO: Filter out things unsuitable for explicit calls, like constructors.
  2226. const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
  2227. for (int i = 0; i < methods.size(); ++i) {
  2228. p_list->push_back(methods[i]->get_method_info());
  2229. }
  2230. }
  2231. bool CSharpScript::has_method(const StringName &p_method) const {
  2232. if (!script_class)
  2233. return false;
  2234. return script_class->has_fetched_method_unknown_params(p_method);
  2235. }
  2236. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2237. if (!script_class)
  2238. return MethodInfo();
  2239. GDMonoClass *top = script_class;
  2240. while (top && top != native) {
  2241. GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
  2242. if (params) {
  2243. return params->get_method_info();
  2244. }
  2245. top = top->get_parent_class();
  2246. }
  2247. return MethodInfo();
  2248. }
  2249. Error CSharpScript::reload(bool p_keep_state) {
  2250. bool has_instances;
  2251. {
  2252. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2253. has_instances = instances.size();
  2254. }
  2255. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  2256. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  2257. if (project_assembly) {
  2258. const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path());
  2259. if (script_metadata_var) {
  2260. Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"];
  2261. const Variant *namespace_ = script_metadata.getptr("namespace");
  2262. const Variant *class_name = script_metadata.getptr("class_name");
  2263. ERR_FAIL_NULL_V(namespace_, ERR_BUG);
  2264. ERR_FAIL_NULL_V(class_name, ERR_BUG);
  2265. GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
  2266. if (klass) {
  2267. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass);
  2268. ERR_FAIL_COND_V(!obj_type, ERR_BUG);
  2269. script_class = klass;
  2270. }
  2271. } else {
  2272. // Missing script metadata. Fallback to legacy method
  2273. script_class = project_assembly->get_object_derived_class(name);
  2274. }
  2275. valid = script_class != NULL;
  2276. if (script_class) {
  2277. #ifdef DEBUG_ENABLED
  2278. print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
  2279. #endif
  2280. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2281. if (!tool) {
  2282. GDMonoClass *nesting_class = script_class->get_nesting_class();
  2283. tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2284. }
  2285. #if TOOLS_ENABLED
  2286. if (!tool) {
  2287. tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2288. }
  2289. #endif
  2290. native = GDMonoUtils::get_class_native_base(script_class);
  2291. CRASH_COND(native == NULL);
  2292. GDMonoClass *base_class = script_class->get_parent_class();
  2293. if (base_class != native)
  2294. base = base_class;
  2295. #ifdef DEBUG_ENABLED
  2296. // For debug builds, we must fetch from all native base methods as well.
  2297. // Native base methods must be fetched before the current class.
  2298. // Not needed if the script class itself is a native class.
  2299. if (script_class != native) {
  2300. GDMonoClass *native_top = native;
  2301. while (native_top) {
  2302. native_top->fetch_methods_with_godot_api_checks(native);
  2303. if (native_top == CACHED_CLASS(GodotObject))
  2304. break;
  2305. native_top = native_top->get_parent_class();
  2306. }
  2307. }
  2308. #endif
  2309. script_class->fetch_methods_with_godot_api_checks(native);
  2310. // Need to fetch method from base classes as well
  2311. GDMonoClass *top = script_class;
  2312. while (top && top != native) {
  2313. top->fetch_methods_with_godot_api_checks(native);
  2314. top = top->get_parent_class();
  2315. }
  2316. load_script_signals(script_class, native);
  2317. _update_exports();
  2318. }
  2319. return OK;
  2320. }
  2321. return ERR_FILE_MISSING_DEPENDENCIES;
  2322. }
  2323. ScriptLanguage *CSharpScript::get_language() const {
  2324. return CSharpLanguage::get_singleton();
  2325. }
  2326. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2327. #ifdef TOOLS_ENABLED
  2328. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  2329. if (E) {
  2330. r_value = E->get();
  2331. return true;
  2332. }
  2333. if (base_cache.is_valid()) {
  2334. return base_cache->get_property_default_value(p_property, r_value);
  2335. }
  2336. #endif
  2337. return false;
  2338. }
  2339. void CSharpScript::update_exports() {
  2340. #ifdef TOOLS_ENABLED
  2341. _update_exports();
  2342. #endif
  2343. }
  2344. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2345. return _signals.has(p_signal);
  2346. }
  2347. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2348. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  2349. MethodInfo mi;
  2350. mi.name = E->key();
  2351. for (int i = 0; i < E->get().size(); i++) {
  2352. PropertyInfo arg;
  2353. arg.name = E->get()[i].name;
  2354. mi.arguments.push_back(arg);
  2355. }
  2356. r_signals->push_back(mi);
  2357. }
  2358. }
  2359. Ref<Script> CSharpScript::get_base_script() const {
  2360. // TODO search in metadata file once we have it, not important any way?
  2361. return Ref<Script>();
  2362. }
  2363. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  2364. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  2365. p_list->push_back(E->value());
  2366. }
  2367. }
  2368. int CSharpScript::get_member_line(const StringName &p_member) const {
  2369. // TODO omnisharp
  2370. return -1;
  2371. }
  2372. Error CSharpScript::load_source_code(const String &p_path) {
  2373. Error ferr = read_all_file_utf8(p_path, source);
  2374. if (ferr != OK) {
  2375. if (ferr == ERR_INVALID_DATA) {
  2376. 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.");
  2377. }
  2378. ERR_FAIL_V(ferr);
  2379. }
  2380. #ifdef TOOLS_ENABLED
  2381. source_changed_cache = true;
  2382. #endif
  2383. return OK;
  2384. }
  2385. StringName CSharpScript::get_script_name() const {
  2386. return name;
  2387. }
  2388. CSharpScript::CSharpScript() :
  2389. script_list(this) {
  2390. _clear();
  2391. #ifdef TOOLS_ENABLED
  2392. source_changed_cache = false;
  2393. placeholder_fallback_enabled = false;
  2394. exports_invalidated = true;
  2395. #endif
  2396. signals_invalidated = true;
  2397. _resource_path_changed();
  2398. #ifdef DEBUG_ENABLED
  2399. {
  2400. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2401. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2402. }
  2403. #endif
  2404. }
  2405. CSharpScript::~CSharpScript() {
  2406. #ifdef DEBUG_ENABLED
  2407. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->script_instances_mutex);
  2408. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2409. #endif
  2410. }
  2411. /*************** RESOURCE ***************/
  2412. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  2413. if (r_error)
  2414. *r_error = ERR_FILE_CANT_OPEN;
  2415. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2416. CSharpScript *script = memnew(CSharpScript);
  2417. Ref<CSharpScript> scriptres(script);
  2418. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2419. Error err = script->load_source_code(p_path);
  2420. ERR_FAIL_COND_V(err != OK, RES());
  2421. #endif
  2422. script->set_path(p_original_path);
  2423. #ifndef TOOLS_ENABLED
  2424. #ifdef DEBUG_ENABLED
  2425. // User is responsible for thread attach/detach
  2426. ERR_EXPLAIN("Thread is not attached");
  2427. CRASH_COND(mono_domain_get() == NULL);
  2428. #endif
  2429. #endif
  2430. #ifdef TOOLS_ENABLED
  2431. MonoDomain *domain = mono_domain_get();
  2432. if (Engine::get_singleton()->is_editor_hint() && domain == NULL) {
  2433. CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
  2434. // Thread is not attached, but we will make an exception in this case
  2435. // because this may be called by one of the editor's worker threads.
  2436. // Attach this thread temporarily to reload the script.
  2437. if (domain) {
  2438. MonoThread *mono_thread = mono_thread_attach(domain);
  2439. CRASH_COND(mono_thread == NULL);
  2440. script->reload();
  2441. mono_thread_detach(mono_thread);
  2442. }
  2443. } else { // just reload it normally
  2444. #endif
  2445. script->reload();
  2446. #ifdef TOOLS_ENABLED
  2447. }
  2448. #endif
  2449. if (r_error)
  2450. *r_error = OK;
  2451. return scriptres;
  2452. }
  2453. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2454. p_extensions->push_back("cs");
  2455. }
  2456. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2457. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2458. }
  2459. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2460. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2461. }
  2462. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  2463. Ref<CSharpScript> sqscr = p_resource;
  2464. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2465. String source = sqscr->get_source_code();
  2466. #ifdef TOOLS_ENABLED
  2467. if (!FileAccess::exists(p_path)) {
  2468. // The file does not yet exists, let's assume the user just created this script
  2469. if (_create_project_solution_if_needed()) {
  2470. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2471. "Compile",
  2472. ProjectSettings::get_singleton()->globalize_path(p_path));
  2473. } else {
  2474. ERR_PRINTS("Failed to create C# project");
  2475. ERR_PRINTS("Cannot add " + p_path + " to the C# project");
  2476. }
  2477. }
  2478. #endif
  2479. Error err;
  2480. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2481. ERR_FAIL_COND_V(err, err);
  2482. file->store_string(source);
  2483. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2484. memdelete(file);
  2485. return ERR_CANT_CREATE;
  2486. }
  2487. file->close();
  2488. memdelete(file);
  2489. #ifdef TOOLS_ENABLED
  2490. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2491. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2492. }
  2493. #endif
  2494. return OK;
  2495. }
  2496. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  2497. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2498. p_extensions->push_back("cs");
  2499. }
  2500. }
  2501. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  2502. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  2503. }
  2504. CSharpLanguage::StringNameCache::StringNameCache() {
  2505. _signal_callback = StaticCString::create("_signal_callback");
  2506. _set = StaticCString::create("_set");
  2507. _get = StaticCString::create("_get");
  2508. _get_property_list = StaticCString::create("_get_property_list");
  2509. _notification = StaticCString::create("_notification");
  2510. _script_source = StaticCString::create("script/source");
  2511. on_before_serialize = StaticCString::create("OnBeforeSerialize");
  2512. on_after_deserialize = StaticCString::create("OnAfterDeserialize");
  2513. dotctor = StaticCString::create(".ctor");
  2514. }