csharp_script.cpp 95 KB

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