script_create_dialog.cpp 35 KB

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