csharp_script.cpp 47 KB

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