script_create_dialog.cpp 38 KB

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