csharp_script.cpp 58 KB

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