script_create_dialog.cpp 37 KB

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