csharp_script.cpp 66 KB

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