csharp_script.cpp 75 KB

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