script_create_dialog.cpp 36 KB

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