script_create_dialog.cpp 34 KB

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