csharp_script.cpp 49 KB

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