script_create_dialog.cpp 37 KB

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