script_create_dialog.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /*************************************************************************/
  2. /* script_create_dialog.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "script_create_dialog.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_saver.h"
  34. #include "core/string/string_builder.h"
  35. #include "editor/create_dialog.h"
  36. #include "editor/editor_file_dialog.h"
  37. #include "editor/editor_file_system.h"
  38. #include "editor/editor_node.h"
  39. #include "editor/editor_paths.h"
  40. #include "editor/editor_scale.h"
  41. #include "editor/editor_settings.h"
  42. static String _get_parent_class_of_script(String p_path) {
  43. if (!ResourceLoader::exists(p_path, "Script")) {
  44. return "Object"; // A script eventually inherits from Object.
  45. }
  46. Ref<Script> script = ResourceLoader::load(p_path, "Script");
  47. ERR_FAIL_COND_V(script.is_null(), "Object");
  48. String class_name;
  49. Ref<Script> base = script->get_base_script();
  50. // Inherits from a built-in class.
  51. if (base.is_null()) {
  52. script->get_language()->get_global_class_name(script->get_path(), &class_name);
  53. return class_name;
  54. }
  55. // Inherits from a script that has class_name.
  56. class_name = script->get_language()->get_global_class_name(base->get_path());
  57. if (!class_name.is_empty()) {
  58. return class_name;
  59. }
  60. // Inherits from a plain script.
  61. return _get_parent_class_of_script(base->get_path());
  62. }
  63. static Vector<String> _get_hierarchy(String p_class_name) {
  64. Vector<String> hierarchy;
  65. String class_name = p_class_name;
  66. while (true) {
  67. // A registered class.
  68. if (ClassDB::class_exists(class_name)) {
  69. hierarchy.push_back(class_name);
  70. class_name = ClassDB::get_parent_class(class_name);
  71. continue;
  72. }
  73. // A class defined in script with class_name.
  74. if (ScriptServer::is_global_class(class_name)) {
  75. hierarchy.push_back(class_name);
  76. Ref<Script> script = EditorNode::get_editor_data().script_class_load_script(class_name);
  77. ERR_BREAK(script.is_null());
  78. class_name = _get_parent_class_of_script(script->get_path());
  79. continue;
  80. }
  81. break;
  82. }
  83. if (hierarchy.is_empty()) {
  84. if (p_class_name.is_valid_identifier()) {
  85. hierarchy.push_back(p_class_name);
  86. }
  87. hierarchy.push_back("Object");
  88. }
  89. return hierarchy;
  90. }
  91. void ScriptCreateDialog::_notification(int p_what) {
  92. switch (p_what) {
  93. case NOTIFICATION_ENTER_TREE: {
  94. String last_language = EditorSettings::get_singleton()->get_project_metadata("script_setup", "last_selected_language", "");
  95. if (!last_language.is_empty()) {
  96. for (int i = 0; i < language_menu->get_item_count(); i++) {
  97. if (language_menu->get_item_text(i) == last_language) {
  98. language_menu->select(i);
  99. current_language = i;
  100. break;
  101. }
  102. }
  103. } else {
  104. language_menu->select(default_language);
  105. }
  106. [[fallthrough]];
  107. }
  108. case NOTIFICATION_THEME_CHANGED: {
  109. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  110. Ref<Texture2D> language_icon = get_theme_icon(ScriptServer::get_language(i)->get_type(), SNAME("EditorIcons"));
  111. if (language_icon.is_valid()) {
  112. language_menu->set_item_icon(i, language_icon);
  113. }
  114. }
  115. path_button->set_icon(get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")));
  116. parent_browse_button->set_icon(get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")));
  117. parent_search_button->set_icon(get_theme_icon(SNAME("ClassList"), SNAME("EditorIcons")));
  118. status_panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("panel"), SNAME("Tree")));
  119. } break;
  120. }
  121. }
  122. void ScriptCreateDialog::_path_hbox_sorted() {
  123. if (is_visible()) {
  124. int filename_start_pos = initial_bp.rfind("/") + 1;
  125. int filename_end_pos = initial_bp.length();
  126. if (!is_built_in) {
  127. file_path->select(filename_start_pos, filename_end_pos);
  128. }
  129. // First set cursor to the end of line to scroll LineEdit view
  130. // to the right and then set the actual cursor position.
  131. file_path->set_caret_column(file_path->get_text().length());
  132. file_path->set_caret_column(filename_start_pos);
  133. file_path->grab_focus();
  134. }
  135. }
  136. bool ScriptCreateDialog::_can_be_built_in() {
  137. return (supports_built_in && built_in_enabled);
  138. }
  139. void ScriptCreateDialog::config(const String &p_base_name, const String &p_base_path, bool p_built_in_enabled, bool p_load_enabled) {
  140. class_name->set_text("");
  141. class_name->deselect();
  142. parent_name->set_text(p_base_name);
  143. parent_name->deselect();
  144. internal_name->set_text("");
  145. if (!p_base_path.is_empty()) {
  146. initial_bp = p_base_path.get_basename();
  147. file_path->set_text(initial_bp + "." + ScriptServer::get_language(language_menu->get_selected())->get_extension());
  148. current_language = language_menu->get_selected();
  149. } else {
  150. initial_bp = "";
  151. file_path->set_text("");
  152. }
  153. file_path->deselect();
  154. built_in_enabled = p_built_in_enabled;
  155. load_enabled = p_load_enabled;
  156. _language_changed(current_language);
  157. _class_name_changed("");
  158. _path_changed(file_path->get_text());
  159. }
  160. void ScriptCreateDialog::set_inheritance_base_type(const String &p_base) {
  161. base_type = p_base;
  162. }
  163. bool ScriptCreateDialog::_validate_parent(const String &p_string) {
  164. if (p_string.length() == 0) {
  165. return false;
  166. }
  167. if (can_inherit_from_file && p_string.is_quoted()) {
  168. String p = p_string.substr(1, p_string.length() - 2);
  169. if (_validate_path(p, true) == "") {
  170. return true;
  171. }
  172. }
  173. return EditorNode::get_editor_data().is_type_recognized(p_string);
  174. }
  175. bool ScriptCreateDialog::_validate_class(const String &p_string) {
  176. if (p_string.length() == 0) {
  177. return false;
  178. }
  179. for (int i = 0; i < p_string.length(); i++) {
  180. if (i == 0) {
  181. // Cannot start with a number.
  182. if (p_string[0] >= '0' && p_string[0] <= '9') {
  183. return false;
  184. }
  185. }
  186. bool valid_char = is_ascii_identifier_char(p_string[i]) || p_string[i] == '.';
  187. if (!valid_char) {
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. String ScriptCreateDialog::_validate_path(const String &p_path, bool p_file_must_exist) {
  194. String p = p_path.strip_edges();
  195. if (p.is_empty()) {
  196. return TTR("Path is empty.");
  197. }
  198. if (p.get_file().get_basename().is_empty()) {
  199. return TTR("Filename is empty.");
  200. }
  201. if (!p.get_file().get_basename().is_valid_filename()) {
  202. return TTR("Filename is invalid.");
  203. }
  204. p = ProjectSettings::get_singleton()->localize_path(p);
  205. if (!p.begins_with("res://")) {
  206. return TTR("Path is not local.");
  207. }
  208. {
  209. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  210. if (da->change_dir(p.get_base_dir()) != OK) {
  211. return TTR("Base path is invalid.");
  212. }
  213. }
  214. {
  215. // Check if file exists.
  216. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  217. if (da->dir_exists(p)) {
  218. return TTR("A directory with the same name exists.");
  219. } else if (p_file_must_exist && !da->file_exists(p)) {
  220. return TTR("File does not exist.");
  221. }
  222. }
  223. // Check file extension.
  224. String extension = p.get_extension();
  225. List<String> extensions;
  226. // Get all possible extensions for script.
  227. for (int l = 0; l < language_menu->get_item_count(); l++) {
  228. ScriptServer::get_language(l)->get_recognized_extensions(&extensions);
  229. }
  230. bool found = false;
  231. bool match = false;
  232. for (const String &E : extensions) {
  233. if (E.nocasecmp_to(extension) == 0) {
  234. found = true;
  235. if (E == ScriptServer::get_language(language_menu->get_selected())->get_extension()) {
  236. match = true;
  237. }
  238. break;
  239. }
  240. }
  241. if (!found) {
  242. return TTR("Invalid extension.");
  243. }
  244. if (!match) {
  245. return TTR("Extension doesn't match chosen language.");
  246. }
  247. // Let ScriptLanguage do custom validation.
  248. String path_error = ScriptServer::get_language(language_menu->get_selected())->validate_path(p);
  249. if (!path_error.is_empty()) {
  250. return path_error;
  251. }
  252. // All checks passed.
  253. return "";
  254. }
  255. String ScriptCreateDialog::_get_class_name() const {
  256. if (has_named_classes) {
  257. return class_name->get_text();
  258. } else {
  259. return ProjectSettings::get_singleton()->localize_path(file_path->get_text()).get_file().get_basename();
  260. }
  261. }
  262. void ScriptCreateDialog::_class_name_changed(const String &p_name) {
  263. is_class_name_valid = _validate_class(class_name->get_text());
  264. _update_dialog();
  265. }
  266. void ScriptCreateDialog::_parent_name_changed(const String &p_parent) {
  267. is_parent_name_valid = _validate_parent(parent_name->get_text());
  268. _update_dialog();
  269. }
  270. void ScriptCreateDialog::_template_changed(int p_template) {
  271. const ScriptLanguage::ScriptTemplate &sinfo = _get_current_template();
  272. // Update last used dictionaries
  273. if (is_using_templates && !parent_name->get_text().begins_with("\"res:")) {
  274. if (sinfo.origin == ScriptLanguage::TemplateLocation::TEMPLATE_PROJECT) {
  275. // Save the last used template for this node into the project dictionary.
  276. Dictionary dic_templates_project = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());
  277. dic_templates_project[parent_name->get_text()] = sinfo.get_hash();
  278. EditorSettings::get_singleton()->set_project_metadata("script_setup", "templates_dictionary", dic_templates_project);
  279. } else {
  280. // Save template info to editor dictionary (not a project template).
  281. templates_dictionary[parent_name->get_text()] = sinfo.get_hash();
  282. // Remove template from project dictionary as we last used an editor level template.
  283. Dictionary dic_templates_project = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());
  284. if (dic_templates_project.has(parent_name->get_text())) {
  285. dic_templates_project.erase(parent_name->get_text());
  286. EditorSettings::get_singleton()->set_project_metadata("script_setup", "templates_dictionary", dic_templates_project);
  287. }
  288. }
  289. }
  290. // Update template label information.
  291. String template_info = String::utf8("• ");
  292. template_info += TTR("Template:");
  293. template_info += " " + sinfo.name;
  294. if (!sinfo.description.is_empty()) {
  295. template_info += " - " + sinfo.description;
  296. }
  297. template_info_label->set_text(template_info);
  298. template_info_label->add_theme_color_override("font_color", get_theme_color(SNAME("success_color"), SNAME("Editor")));
  299. }
  300. void ScriptCreateDialog::ok_pressed() {
  301. if (is_new_script_created) {
  302. _create_new();
  303. } else {
  304. _load_exist();
  305. }
  306. EditorSettings::get_singleton()->save();
  307. is_new_script_created = true;
  308. _update_dialog();
  309. }
  310. void ScriptCreateDialog::_create_new() {
  311. String cname_param = _get_class_name();
  312. Ref<Script> scr;
  313. const ScriptLanguage::ScriptTemplate sinfo = _get_current_template();
  314. String parent_class = parent_name->get_text();
  315. if (!ClassDB::class_exists(parent_class) && !ScriptServer::is_global_class(parent_class)) {
  316. // If base is a custom type, replace with script path instead.
  317. const EditorData::CustomType *type = EditorNode::get_editor_data().get_custom_type_by_name(parent_class);
  318. ERR_FAIL_NULL(type);
  319. parent_class = "\"" + type->script->get_path() + "\"";
  320. }
  321. scr = ScriptServer::get_language(language_menu->get_selected())->make_template(sinfo.content, cname_param, parent_class);
  322. if (has_named_classes) {
  323. String cname = class_name->get_text();
  324. if (cname.length()) {
  325. scr->set_name(cname);
  326. }
  327. }
  328. if (is_built_in) {
  329. scr->set_name(internal_name->get_text());
  330. } else {
  331. String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());
  332. scr->set_path(lpath);
  333. Error err = ResourceSaver::save(scr, lpath, ResourceSaver::FLAG_CHANGE_PATH);
  334. if (err != OK) {
  335. alert->set_text(TTR("Error - Could not create script in filesystem."));
  336. alert->popup_centered();
  337. return;
  338. }
  339. }
  340. emit_signal(SNAME("script_created"), scr);
  341. hide();
  342. }
  343. void ScriptCreateDialog::_load_exist() {
  344. String path = file_path->get_text();
  345. Ref<Resource> p_script = ResourceLoader::load(path, "Script");
  346. if (p_script.is_null()) {
  347. alert->set_text(vformat(TTR("Error loading script from %s"), path));
  348. alert->popup_centered();
  349. return;
  350. }
  351. emit_signal(SNAME("script_created"), p_script);
  352. hide();
  353. }
  354. void ScriptCreateDialog::_language_changed(int l) {
  355. language = ScriptServer::get_language(l);
  356. has_named_classes = language->has_named_classes();
  357. can_inherit_from_file = language->can_inherit_from_file();
  358. supports_built_in = language->supports_builtin_mode();
  359. if (!supports_built_in) {
  360. is_built_in = false;
  361. }
  362. String selected_ext = "." + language->get_extension();
  363. String path = file_path->get_text();
  364. String extension = "";
  365. if (!path.is_empty()) {
  366. if (path.contains(".")) {
  367. extension = path.get_extension();
  368. }
  369. if (extension.length() == 0) {
  370. // Add extension if none.
  371. path += selected_ext;
  372. _path_changed(path);
  373. } else {
  374. // Change extension by selected language.
  375. List<String> extensions;
  376. // Get all possible extensions for script.
  377. for (int m = 0; m < language_menu->get_item_count(); m++) {
  378. ScriptServer::get_language(m)->get_recognized_extensions(&extensions);
  379. }
  380. for (const String &E : extensions) {
  381. if (E.nocasecmp_to(extension) == 0) {
  382. path = path.get_basename() + selected_ext;
  383. _path_changed(path);
  384. break;
  385. }
  386. }
  387. }
  388. } else {
  389. path = "class" + selected_ext;
  390. _path_changed(path);
  391. }
  392. file_path->set_text(path);
  393. EditorSettings::get_singleton()->set_project_metadata("script_setup", "last_selected_language", language_menu->get_item_text(language_menu->get_selected()));
  394. _parent_name_changed(parent_name->get_text());
  395. _update_dialog();
  396. }
  397. void ScriptCreateDialog::_built_in_pressed() {
  398. if (internal->is_pressed()) {
  399. is_built_in = true;
  400. is_new_script_created = true;
  401. } else {
  402. is_built_in = false;
  403. _path_changed(file_path->get_text());
  404. }
  405. _update_dialog();
  406. }
  407. void ScriptCreateDialog::_use_template_pressed() {
  408. is_using_templates = use_templates->is_pressed();
  409. _update_dialog();
  410. }
  411. void ScriptCreateDialog::_browse_path(bool browse_parent, bool p_save) {
  412. is_browsing_parent = browse_parent;
  413. if (p_save) {
  414. file_browse->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
  415. file_browse->set_title(TTR("Open Script / Choose Location"));
  416. file_browse->set_ok_button_text(TTR("Open"));
  417. } else {
  418. file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  419. file_browse->set_title(TTR("Open Script"));
  420. }
  421. file_browse->set_disable_overwrite_warning(true);
  422. file_browse->clear_filters();
  423. List<String> extensions;
  424. int lang = language_menu->get_selected();
  425. ScriptServer::get_language(lang)->get_recognized_extensions(&extensions);
  426. for (const String &E : extensions) {
  427. file_browse->add_filter("*." + E);
  428. }
  429. file_browse->set_current_path(file_path->get_text());
  430. file_browse->popup_file_dialog();
  431. }
  432. void ScriptCreateDialog::_file_selected(const String &p_file) {
  433. String path = ProjectSettings::get_singleton()->localize_path(p_file);
  434. if (is_browsing_parent) {
  435. parent_name->set_text("\"" + path + "\"");
  436. _parent_name_changed(parent_name->get_text());
  437. } else {
  438. file_path->set_text(path);
  439. _path_changed(path);
  440. String filename = path.get_file().get_basename();
  441. int select_start = path.rfind(filename);
  442. file_path->select(select_start, select_start + filename.length());
  443. file_path->set_caret_column(select_start + filename.length());
  444. file_path->grab_focus();
  445. }
  446. }
  447. void ScriptCreateDialog::_create() {
  448. parent_name->set_text(select_class->get_selected_type().split(" ")[0]);
  449. _parent_name_changed(parent_name->get_text());
  450. }
  451. void ScriptCreateDialog::_browse_class_in_tree() {
  452. select_class->set_base_type(base_type);
  453. select_class->popup_create(true);
  454. select_class->set_title(vformat(TTR("Inherit %s"), base_type));
  455. select_class->set_ok_button_text(TTR("Inherit"));
  456. }
  457. void ScriptCreateDialog::_path_changed(const String &p_path) {
  458. if (is_built_in) {
  459. return;
  460. }
  461. is_path_valid = false;
  462. is_new_script_created = true;
  463. String path_error = _validate_path(p_path, false);
  464. if (!path_error.is_empty()) {
  465. _msg_path_valid(false, path_error);
  466. _update_dialog();
  467. return;
  468. }
  469. // Check if file exists.
  470. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  471. String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges());
  472. if (da->file_exists(p)) {
  473. is_new_script_created = false;
  474. _msg_path_valid(true, TTR("File exists, it will be reused."));
  475. }
  476. is_path_valid = true;
  477. _update_dialog();
  478. }
  479. void ScriptCreateDialog::_path_submitted(const String &p_path) {
  480. ok_pressed();
  481. }
  482. void ScriptCreateDialog::_msg_script_valid(bool valid, const String &p_msg) {
  483. error_label->set_text(String::utf8("• ") + p_msg);
  484. if (valid) {
  485. error_label->add_theme_color_override("font_color", get_theme_color(SNAME("success_color"), SNAME("Editor")));
  486. } else {
  487. error_label->add_theme_color_override("font_color", get_theme_color(SNAME("error_color"), SNAME("Editor")));
  488. }
  489. }
  490. void ScriptCreateDialog::_msg_path_valid(bool valid, const String &p_msg) {
  491. path_error_label->set_text(String::utf8("• ") + p_msg);
  492. if (valid) {
  493. path_error_label->add_theme_color_override("font_color", get_theme_color(SNAME("success_color"), SNAME("Editor")));
  494. } else {
  495. path_error_label->add_theme_color_override("font_color", get_theme_color(SNAME("error_color"), SNAME("Editor")));
  496. }
  497. }
  498. void ScriptCreateDialog::_update_template_menu() {
  499. bool is_language_using_templates = language->is_using_templates();
  500. template_menu->set_disabled(false);
  501. template_menu->clear();
  502. template_list.clear();
  503. if (is_language_using_templates) {
  504. // Get the latest templates used for each type of node from project settings then global settings.
  505. Dictionary last_local_templates = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());
  506. String inherits_base_type = parent_name->get_text();
  507. // If it inherits from a script, get its parent class first.
  508. if (inherits_base_type[0] == '"') {
  509. inherits_base_type = _get_parent_class_of_script(inherits_base_type.unquote());
  510. }
  511. // Get all ancestor node for selected base node.
  512. // There templates will also fit the base node.
  513. Vector<String> hierarchy = _get_hierarchy(inherits_base_type);
  514. int last_used_template = -1;
  515. int preselected_template = -1;
  516. int previous_ancestor_level = -1;
  517. // Templates can be stored in tree different locations.
  518. Vector<ScriptLanguage::TemplateLocation> template_locations;
  519. template_locations.append(ScriptLanguage::TEMPLATE_PROJECT);
  520. template_locations.append(ScriptLanguage::TEMPLATE_EDITOR);
  521. template_locations.append(ScriptLanguage::TEMPLATE_BUILT_IN);
  522. for (const ScriptLanguage::TemplateLocation &template_location : template_locations) {
  523. String display_name = _get_script_origin_label(template_location);
  524. bool separator = false;
  525. int ancestor_level = 0;
  526. for (const String &current_node : hierarchy) {
  527. Vector<ScriptLanguage::ScriptTemplate> templates_found;
  528. if (template_location == ScriptLanguage::TEMPLATE_BUILT_IN) {
  529. templates_found = language->get_built_in_templates(current_node);
  530. } else {
  531. String template_directory;
  532. if (template_location == ScriptLanguage::TEMPLATE_PROJECT) {
  533. template_directory = EditorPaths::get_singleton()->get_project_script_templates_dir();
  534. } else {
  535. template_directory = EditorPaths::get_singleton()->get_script_templates_dir();
  536. }
  537. templates_found = _get_user_templates(language, current_node, template_directory, template_location);
  538. }
  539. if (!templates_found.is_empty()) {
  540. if (!separator) {
  541. template_menu->add_separator();
  542. template_menu->set_item_text(-1, display_name);
  543. separator = true;
  544. }
  545. for (ScriptLanguage::ScriptTemplate &t : templates_found) {
  546. template_menu->add_item(t.inherit + ": " + t.name);
  547. int id = template_menu->get_item_count() - 1;
  548. // Check if this template should be preselected if node isn't in the last used dictionary.
  549. if (ancestor_level < previous_ancestor_level || previous_ancestor_level == -1) {
  550. previous_ancestor_level = ancestor_level;
  551. preselected_template = id;
  552. }
  553. // Check for last used template for this node in project settings then in global settings.
  554. if (last_local_templates.has(parent_name->get_text()) && t.get_hash() == String(last_local_templates[parent_name->get_text()])) {
  555. last_used_template = id;
  556. } else if (last_used_template == -1 && templates_dictionary.has(parent_name->get_text()) && t.get_hash() == String(templates_dictionary[parent_name->get_text()])) {
  557. last_used_template = id;
  558. }
  559. t.id = id;
  560. template_list.push_back(t);
  561. String icon = has_theme_icon(t.inherit, SNAME("EditorIcons")) ? t.inherit : "Object";
  562. template_menu->set_item_icon(id, get_theme_icon(icon, SNAME("EditorIcons")));
  563. }
  564. }
  565. ancestor_level++;
  566. }
  567. }
  568. if (last_used_template != -1) {
  569. template_menu->select(last_used_template);
  570. } else if (preselected_template != -1) {
  571. template_menu->select(preselected_template);
  572. }
  573. }
  574. _template_changed(template_menu->get_selected());
  575. }
  576. void ScriptCreateDialog::_update_dialog() {
  577. // "Add Script Dialog" GUI logic and script checks.
  578. _update_template_menu();
  579. bool script_ok = true;
  580. // Is script path/name valid (order from top to bottom)?
  581. if (!is_built_in && !is_path_valid) {
  582. _msg_script_valid(false, TTR("Invalid path."));
  583. script_ok = false;
  584. }
  585. if (has_named_classes && (is_new_script_created && !is_class_name_valid)) {
  586. _msg_script_valid(false, TTR("Invalid class name."));
  587. script_ok = false;
  588. }
  589. if (!is_parent_name_valid && is_new_script_created) {
  590. _msg_script_valid(false, TTR("Invalid inherited parent name or path."));
  591. script_ok = false;
  592. }
  593. if (script_ok) {
  594. _msg_script_valid(true, TTR("Script path/name is valid."));
  595. }
  596. // Does script have named classes?
  597. if (has_named_classes) {
  598. if (is_new_script_created) {
  599. class_name->set_editable(true);
  600. class_name->set_placeholder(TTR("Allowed: a-z, A-Z, 0-9, _ and ."));
  601. Color placeholder_color = class_name->get_theme_color(SNAME("font_placeholder_color"));
  602. placeholder_color.a = 0.3;
  603. class_name->add_theme_color_override("font_placeholder_color", placeholder_color);
  604. } else {
  605. class_name->set_editable(false);
  606. }
  607. } else {
  608. class_name->set_editable(false);
  609. class_name->set_placeholder(TTR("N/A"));
  610. Color placeholder_color = class_name->get_theme_color(SNAME("font_placeholder_color"));
  611. placeholder_color.a = 1;
  612. class_name->add_theme_color_override("font_placeholder_color", placeholder_color);
  613. class_name->set_text("");
  614. }
  615. // Is script Built-in?
  616. if (is_built_in) {
  617. file_path->set_editable(false);
  618. path_button->set_disabled(true);
  619. re_check_path = true;
  620. } else {
  621. file_path->set_editable(true);
  622. path_button->set_disabled(false);
  623. if (re_check_path) {
  624. re_check_path = false;
  625. _path_changed(file_path->get_text());
  626. }
  627. }
  628. if (!_can_be_built_in()) {
  629. internal->set_pressed(false);
  630. }
  631. internal->set_disabled(!_can_be_built_in());
  632. // Is Script created or loaded from existing file?
  633. builtin_warning_label->set_visible(is_built_in);
  634. path_controls[0]->set_visible(!is_built_in);
  635. path_controls[1]->set_visible(!is_built_in);
  636. name_controls[0]->set_visible(is_built_in);
  637. name_controls[1]->set_visible(is_built_in);
  638. // Check if the script name is the same as the parent class.
  639. // This warning isn't relevant if the script is built-in.
  640. script_name_warning_label->set_visible(!is_built_in && _get_class_name() == parent_name->get_text());
  641. bool is_new_file = is_built_in || is_new_script_created;
  642. parent_name->set_editable(is_new_file);
  643. parent_search_button->set_disabled(!is_new_file);
  644. parent_browse_button->set_disabled(!is_new_file || !can_inherit_from_file);
  645. template_inactive_message = "";
  646. String button_text = is_new_file ? TTR("Create") : TTR("Load");
  647. set_ok_button_text(button_text);
  648. if (is_new_file) {
  649. if (is_built_in) {
  650. _msg_path_valid(true, TTR("Built-in script (into scene file)."));
  651. }
  652. if (is_new_script_created && is_path_valid) {
  653. _msg_path_valid(true, TTR("Will create a new script file."));
  654. }
  655. } else {
  656. if (load_enabled) {
  657. template_inactive_message = TTR("Using existing script file.");
  658. if (is_path_valid) {
  659. _msg_path_valid(true, TTR("Will load an existing script file."));
  660. }
  661. } else {
  662. template_inactive_message = TTR("Using existing script file.");
  663. _msg_path_valid(false, TTR("Script file already exists."));
  664. script_ok = false;
  665. }
  666. }
  667. // Show templates list if needed.
  668. if (is_using_templates) {
  669. // Check if at least one suitable template has been found.
  670. if (template_menu->get_item_count() == 0 && template_inactive_message.is_empty()) {
  671. template_inactive_message = TTR("No suitable template.");
  672. }
  673. } else {
  674. template_inactive_message = TTR("Empty");
  675. }
  676. if (!template_inactive_message.is_empty()) {
  677. template_menu->set_disabled(true);
  678. template_menu->clear();
  679. template_menu->add_item(template_inactive_message);
  680. }
  681. template_info_label->set_visible(!template_menu->is_disabled());
  682. get_ok_button()->set_disabled(!script_ok);
  683. Callable entered_call = callable_mp(this, &ScriptCreateDialog::_path_submitted);
  684. if (script_ok) {
  685. if (!file_path->is_connected("text_submitted", entered_call)) {
  686. file_path->connect("text_submitted", entered_call);
  687. }
  688. } else if (file_path->is_connected("text_submitted", entered_call)) {
  689. file_path->disconnect("text_submitted", entered_call);
  690. }
  691. }
  692. ScriptLanguage::ScriptTemplate ScriptCreateDialog::_get_current_template() const {
  693. int selected_index = template_menu->get_selected();
  694. for (const ScriptLanguage::ScriptTemplate &t : template_list) {
  695. if (is_using_templates) {
  696. if (t.id == selected_index) {
  697. return t;
  698. }
  699. } else {
  700. // Using empty built-in template if templates are disabled.
  701. if (t.origin == ScriptLanguage::TemplateLocation::TEMPLATE_BUILT_IN && t.name == "Empty") {
  702. return t;
  703. }
  704. }
  705. }
  706. return ScriptLanguage::ScriptTemplate();
  707. }
  708. Vector<ScriptLanguage::ScriptTemplate> ScriptCreateDialog::_get_user_templates(const ScriptLanguage *p_language, const StringName &p_object, const String &p_dir, const ScriptLanguage::TemplateLocation &p_origin) const {
  709. Vector<ScriptLanguage::ScriptTemplate> user_templates;
  710. String extension = p_language->get_extension();
  711. String dir_path = p_dir.path_join(p_object);
  712. Ref<DirAccess> d = DirAccess::open(dir_path);
  713. if (d.is_valid()) {
  714. d->list_dir_begin();
  715. String file = d->get_next();
  716. while (file != String()) {
  717. if (file.get_extension() == extension) {
  718. user_templates.append(_parse_template(p_language, dir_path, file, p_origin, p_object));
  719. }
  720. file = d->get_next();
  721. }
  722. d->list_dir_end();
  723. }
  724. return user_templates;
  725. }
  726. ScriptLanguage::ScriptTemplate ScriptCreateDialog::_parse_template(const ScriptLanguage *p_language, const String &p_path, const String &p_filename, const ScriptLanguage::TemplateLocation &p_origin, const String &p_inherits) const {
  727. ScriptLanguage::ScriptTemplate script_template = ScriptLanguage::ScriptTemplate();
  728. script_template.origin = p_origin;
  729. script_template.inherit = p_inherits;
  730. String space_indent = " ";
  731. // Get meta delimiter
  732. String meta_delimiter = String();
  733. List<String> comment_delimiters;
  734. p_language->get_comment_delimiters(&comment_delimiters);
  735. for (const String &script_delimiter : comment_delimiters) {
  736. if (!script_delimiter.contains(" ")) {
  737. meta_delimiter = script_delimiter;
  738. break;
  739. }
  740. }
  741. String meta_prefix = meta_delimiter + " meta-";
  742. // Parse file for meta-information and script content
  743. Error err;
  744. Ref<FileAccess> file = FileAccess::open(p_path.path_join(p_filename), FileAccess::READ, &err);
  745. if (!err) {
  746. while (!file->eof_reached()) {
  747. String line = file->get_line();
  748. if (line.begins_with(meta_prefix)) {
  749. // Store meta information
  750. line = line.substr(meta_prefix.length(), -1);
  751. if (line.begins_with("name")) {
  752. script_template.name = line.substr(5, -1).strip_edges();
  753. }
  754. if (line.begins_with("description")) {
  755. script_template.description = line.substr(12, -1).strip_edges();
  756. }
  757. if (line.begins_with("space-indent")) {
  758. String indent_value = line.substr(17, -1).strip_edges();
  759. if (indent_value.is_valid_int()) {
  760. space_indent = "";
  761. for (int i = 0; i < indent_value.to_int(); i++) {
  762. space_indent += " ";
  763. }
  764. } else {
  765. WARN_PRINT(vformat("Template meta-use_space_indent need to be a valid integer value. Found %s.", indent_value));
  766. }
  767. }
  768. } else {
  769. // Store script
  770. if (space_indent != "") {
  771. line = line.replace(space_indent, "_TS_");
  772. }
  773. script_template.content += line.replace("\t", "_TS_") + "\n";
  774. }
  775. }
  776. }
  777. script_template.content = script_template.content.lstrip("\n");
  778. // Get name from file name if no name in meta information
  779. if (script_template.name == String()) {
  780. script_template.name = p_filename.get_basename().capitalize();
  781. }
  782. return script_template;
  783. }
  784. String ScriptCreateDialog::_get_script_origin_label(const ScriptLanguage::TemplateLocation &p_origin) const {
  785. switch (p_origin) {
  786. case ScriptLanguage::TEMPLATE_BUILT_IN:
  787. return TTR("Built-in");
  788. case ScriptLanguage::TEMPLATE_EDITOR:
  789. return TTR("Editor");
  790. case ScriptLanguage::TEMPLATE_PROJECT:
  791. return TTR("Project");
  792. }
  793. return "";
  794. }
  795. void ScriptCreateDialog::_bind_methods() {
  796. ClassDB::bind_method(D_METHOD("config", "inherits", "path", "built_in_enabled", "load_enabled"), &ScriptCreateDialog::config, DEFVAL(true), DEFVAL(true));
  797. ADD_SIGNAL(MethodInfo("script_created", PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script")));
  798. }
  799. ScriptCreateDialog::ScriptCreateDialog() {
  800. /* Main Controls */
  801. GridContainer *gc = memnew(GridContainer);
  802. gc->set_columns(2);
  803. /* Information Messages Field */
  804. VBoxContainer *vb = memnew(VBoxContainer);
  805. error_label = memnew(Label);
  806. vb->add_child(error_label);
  807. path_error_label = memnew(Label);
  808. vb->add_child(path_error_label);
  809. builtin_warning_label = memnew(Label);
  810. builtin_warning_label->set_text(
  811. TTR("Note: Built-in scripts have some limitations and can't be edited using an external editor."));
  812. vb->add_child(builtin_warning_label);
  813. builtin_warning_label->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
  814. builtin_warning_label->hide();
  815. script_name_warning_label = memnew(Label);
  816. script_name_warning_label->set_text(
  817. TTR("Warning: Having the script name be the same as a built-in type is usually not desired."));
  818. vb->add_child(script_name_warning_label);
  819. script_name_warning_label->add_theme_color_override("font_color", Color(1, 0.85, 0.4));
  820. script_name_warning_label->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
  821. script_name_warning_label->hide();
  822. template_info_label = memnew(Label);
  823. vb->add_child(template_info_label);
  824. template_info_label->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
  825. status_panel = memnew(PanelContainer);
  826. status_panel->set_h_size_flags(Control::SIZE_FILL);
  827. status_panel->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  828. status_panel->add_child(vb);
  829. /* Spacing */
  830. Control *spacing = memnew(Control);
  831. spacing->set_custom_minimum_size(Size2(0, 10 * EDSCALE));
  832. vb = memnew(VBoxContainer);
  833. vb->add_child(gc);
  834. vb->add_child(spacing);
  835. vb->add_child(status_panel);
  836. add_child(vb);
  837. /* Language */
  838. language_menu = memnew(OptionButton);
  839. language_menu->set_custom_minimum_size(Size2(350, 0) * EDSCALE);
  840. language_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  841. gc->add_child(memnew(Label(TTR("Language:"))));
  842. gc->add_child(language_menu);
  843. default_language = -1;
  844. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  845. String lang = ScriptServer::get_language(i)->get_name();
  846. language_menu->add_item(lang);
  847. if (lang == "GDScript") {
  848. default_language = i;
  849. }
  850. }
  851. if (default_language >= 0) {
  852. language_menu->select(default_language);
  853. }
  854. current_language = default_language;
  855. language_menu->connect("item_selected", callable_mp(this, &ScriptCreateDialog::_language_changed));
  856. /* Inherits */
  857. base_type = "Object";
  858. HBoxContainer *hb = memnew(HBoxContainer);
  859. hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  860. parent_name = memnew(LineEdit);
  861. parent_name->connect("text_changed", callable_mp(this, &ScriptCreateDialog::_parent_name_changed));
  862. parent_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  863. hb->add_child(parent_name);
  864. parent_search_button = memnew(Button);
  865. parent_search_button->connect("pressed", callable_mp(this, &ScriptCreateDialog::_browse_class_in_tree));
  866. hb->add_child(parent_search_button);
  867. parent_browse_button = memnew(Button);
  868. parent_browse_button->connect("pressed", callable_mp(this, &ScriptCreateDialog::_browse_path).bind(true, false));
  869. hb->add_child(parent_browse_button);
  870. gc->add_child(memnew(Label(TTR("Inherits:"))));
  871. gc->add_child(hb);
  872. /* Class Name */
  873. class_name = memnew(LineEdit);
  874. class_name->connect("text_changed", callable_mp(this, &ScriptCreateDialog::_class_name_changed));
  875. class_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  876. gc->add_child(memnew(Label(TTR("Class Name:"))));
  877. gc->add_child(class_name);
  878. /* Templates */
  879. gc->add_child(memnew(Label(TTR("Template:"))));
  880. HBoxContainer *template_hb = memnew(HBoxContainer);
  881. template_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  882. use_templates = memnew(CheckBox);
  883. use_templates->set_pressed(is_using_templates);
  884. use_templates->connect("pressed", callable_mp(this, &ScriptCreateDialog::_use_template_pressed));
  885. template_hb->add_child(use_templates);
  886. template_inactive_message = "";
  887. template_menu = memnew(OptionButton);
  888. template_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  889. template_menu->connect("item_selected", callable_mp(this, &ScriptCreateDialog::_template_changed));
  890. template_hb->add_child(template_menu);
  891. gc->add_child(template_hb);
  892. /* Built-in Script */
  893. internal = memnew(CheckBox);
  894. internal->set_text(TTR("On"));
  895. internal->connect("pressed", callable_mp(this, &ScriptCreateDialog::_built_in_pressed));
  896. gc->add_child(memnew(Label(TTR("Built-in Script:"))));
  897. gc->add_child(internal);
  898. /* Path */
  899. hb = memnew(HBoxContainer);
  900. hb->connect("sort_children", callable_mp(this, &ScriptCreateDialog::_path_hbox_sorted));
  901. file_path = memnew(LineEdit);
  902. file_path->connect("text_changed", callable_mp(this, &ScriptCreateDialog::_path_changed));
  903. file_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  904. hb->add_child(file_path);
  905. path_button = memnew(Button);
  906. path_button->connect("pressed", callable_mp(this, &ScriptCreateDialog::_browse_path).bind(false, true));
  907. hb->add_child(path_button);
  908. Label *label = memnew(Label(TTR("Path:")));
  909. gc->add_child(label);
  910. gc->add_child(hb);
  911. path_controls[0] = label;
  912. path_controls[1] = hb;
  913. /* Name */
  914. internal_name = memnew(LineEdit);
  915. internal_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  916. internal_name->connect("text_submitted", callable_mp(this, &ScriptCreateDialog::_path_submitted));
  917. label = memnew(Label(TTR("Name:")));
  918. gc->add_child(label);
  919. gc->add_child(internal_name);
  920. name_controls[0] = label;
  921. name_controls[1] = internal_name;
  922. label->hide();
  923. internal_name->hide();
  924. /* Dialog Setup */
  925. select_class = memnew(CreateDialog);
  926. select_class->connect("create", callable_mp(this, &ScriptCreateDialog::_create));
  927. add_child(select_class);
  928. file_browse = memnew(EditorFileDialog);
  929. file_browse->connect("file_selected", callable_mp(this, &ScriptCreateDialog::_file_selected));
  930. file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  931. add_child(file_browse);
  932. set_ok_button_text(TTR("Create"));
  933. alert = memnew(AcceptDialog);
  934. alert->get_label()->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
  935. alert->get_label()->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  936. alert->get_label()->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  937. alert->get_label()->set_custom_minimum_size(Size2(325, 60) * EDSCALE);
  938. add_child(alert);
  939. set_hide_on_ok(false);
  940. set_title(TTR("Attach Node Script"));
  941. }