script_create_dialog.cpp 35 KB

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