script_create_dialog.cpp 36 KB

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