script_create_dialog.cpp 38 KB

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