script_create_dialog.cpp 35 KB

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