script_create_dialog.cpp 36 KB

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