script_create_dialog.cpp 36 KB

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