script_create_dialog.cpp 38 KB

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