Path: blob/master/editor/script/script_create_dialog.cpp
9903 views
/**************************************************************************/1/* script_create_dialog.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "script_create_dialog.h"3132#include "core/config/project_settings.h"33#include "core/io/file_access.h"34#include "core/io/resource_saver.h"35#include "editor/editor_node.h"36#include "editor/editor_string_names.h"37#include "editor/file_system/editor_file_system.h"38#include "editor/file_system/editor_paths.h"39#include "editor/gui/create_dialog.h"40#include "editor/gui/editor_file_dialog.h"41#include "editor/gui/editor_validation_panel.h"42#include "editor/settings/editor_settings.h"43#include "editor/themes/editor_scale.h"44#include "scene/gui/grid_container.h"45#include "scene/gui/line_edit.h"46#include "scene/theme/theme_db.h"4748static String _get_parent_class_of_script(const String &p_path) {49if (!ResourceLoader::exists(p_path, "Script")) {50return "Object"; // A script eventually inherits from Object.51}5253Ref<Script> script = ResourceLoader::load(p_path, "Script");54ERR_FAIL_COND_V(script.is_null(), "Object");5556String class_name;57Ref<Script> base = script->get_base_script();5859// Inherits from a built-in class.60if (base.is_null()) {61// We only care about the referenced class_name.62_ALLOW_DISCARD_ script->get_language()->get_global_class_name(script->get_path(), &class_name);63return class_name;64}6566// Inherits from a script that has class_name.67class_name = script->get_language()->get_global_class_name(base->get_path());68if (!class_name.is_empty()) {69return class_name;70}7172// Inherits from a plain script.73return _get_parent_class_of_script(base->get_path());74}7576static Vector<String> _get_hierarchy(const String &p_class_name) {77Vector<String> hierarchy;7879String class_name = p_class_name;80while (true) {81// A registered class.82if (ClassDB::class_exists(class_name)) {83hierarchy.push_back(class_name);8485class_name = ClassDB::get_parent_class(class_name);86continue;87}8889// A class defined in script with class_name.90if (ScriptServer::is_global_class(class_name)) {91hierarchy.push_back(class_name);9293Ref<Script> script = EditorNode::get_editor_data().script_class_load_script(class_name);94ERR_BREAK(script.is_null());95class_name = _get_parent_class_of_script(script->get_path());96continue;97}9899break;100}101102if (hierarchy.is_empty()) {103if (p_class_name.is_valid_ascii_identifier()) {104hierarchy.push_back(p_class_name);105}106hierarchy.push_back("Object");107}108109return hierarchy;110}111112void ScriptCreateDialog::_notification(int p_what) {113switch (p_what) {114case NOTIFICATION_ENTER_TREE: {115String last_language = EditorSettings::get_singleton()->get_project_metadata("script_setup", "last_selected_language", "");116if (!last_language.is_empty()) {117for (int i = 0; i < language_menu->get_item_count(); i++) {118if (language_menu->get_item_text(i) == last_language) {119language_menu->select(i);120break;121}122}123} else {124language_menu->select(default_language);125}126is_using_templates = EDITOR_DEF("_script_setup_use_script_templates", false);127use_templates->set_pressed(is_using_templates);128} break;129130case NOTIFICATION_THEME_CHANGED: {131const int icon_size = get_theme_constant(SNAME("class_icon_size"), EditorStringName(Editor));132133EditorData &ed = EditorNode::get_editor_data();134135for (int i = 0; i < ScriptServer::get_language_count(); i++) {136// Check if the extension has an icon first.137String script_type = ScriptServer::get_language(i)->get_type();138Ref<Texture2D> language_icon = get_editor_theme_icon(script_type);139if (language_icon.is_null() || language_icon == ThemeDB::get_singleton()->get_fallback_icon()) {140// The theme doesn't have an icon for this language, ask the extensions.141Ref<Texture2D> extension_language_icon = ed.extension_class_get_icon(script_type);142if (extension_language_icon.is_valid()) {143language_menu->get_popup()->set_item_icon_max_width(i, icon_size);144language_icon = extension_language_icon;145}146}147148if (language_icon.is_valid()) {149language_menu->set_item_icon(i, language_icon);150}151}152153path_button->set_button_icon(get_editor_theme_icon(SNAME("Folder")));154parent_browse_button->set_button_icon(get_editor_theme_icon(SNAME("Folder")));155parent_search_button->set_button_icon(get_editor_theme_icon(SNAME("ClassList")));156} break;157}158}159160void ScriptCreateDialog::_path_hbox_sorted() {161if (is_visible()) {162int filename_start_pos = file_path->get_text().rfind_char('/') + 1;163int filename_end_pos = file_path->get_text().get_basename().length();164165if (!is_built_in) {166file_path->select(filename_start_pos, filename_end_pos);167}168169// First set cursor to the end of line to scroll LineEdit view170// to the right and then set the actual cursor position.171file_path->set_caret_column(file_path->get_text().length());172file_path->set_caret_column(filename_start_pos);173174file_path->grab_focus();175}176}177178bool ScriptCreateDialog::_can_be_built_in() {179return (supports_built_in && built_in_enabled);180}181182String ScriptCreateDialog::_adjust_file_path(const String &p_base_path) const {183if (p_base_path.is_empty()) {184return p_base_path;185}186187String base_dir = p_base_path.get_base_dir();188String file_name = p_base_path.get_file().get_basename();189file_name = EditorNode::adjust_script_name_casing(file_name, language->preferred_file_name_casing());190String extension = language->get_extension();191return base_dir.path_join(file_name + "." + extension);192}193194void ScriptCreateDialog::config(const String &p_base_name, const String &p_base_path, bool p_built_in_enabled, bool p_load_enabled) {195parent_name->set_text(p_base_name);196parent_name->deselect();197built_in_name->set_text("");198199file_path->set_text(p_base_path);200file_path->deselect();201202built_in_enabled = p_built_in_enabled;203load_enabled = p_load_enabled;204205_language_changed(language_menu->get_selected());206207if (_can_be_built_in()) {208built_in->set_pressed(EditorSettings::get_singleton()->get_project_metadata("script_setup", "create_built_in_script", false));209_built_in_pressed();210}211}212213void ScriptCreateDialog::set_inheritance_base_type(const String &p_base) {214base_type = p_base;215}216217bool ScriptCreateDialog::_validate_parent(const String &p_string) {218if (p_string.length() == 0) {219return false;220}221222if (can_inherit_from_file && p_string.is_quoted()) {223String p = p_string.substr(1, p_string.length() - 2);224if (_validate_path(p, true).is_empty()) {225return true;226}227}228229return EditorNode::get_editor_data().is_type_recognized(p_string);230}231232String ScriptCreateDialog::_validate_path(const String &p_path, bool p_file_must_exist, bool *r_path_valid) {233String p = p_path.strip_edges();234if (r_path_valid) {235*r_path_valid = false;236}237238if (p.is_empty()) {239return TTR("Path is empty.");240}241if (p.get_file().get_basename().is_empty()) {242return TTR("Filename is empty.");243}244245if (!p.get_file().get_basename().is_valid_filename()) {246return TTR("Filename is invalid.");247}248if (p.get_file().begins_with(".")) {249return TTR("Name begins with a dot.");250}251252p = ProjectSettings::get_singleton()->localize_path(p);253if (!p.begins_with("res://")) {254return TTR("Path is not local.");255}256257{258Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);259if (da->change_dir(p.get_base_dir()) != OK) {260return TTR("Base path is invalid.");261}262}263264{265// Check if file exists.266Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);267if (da->dir_exists(p)) {268return TTR("A directory with the same name exists.");269} else if (p_file_must_exist && !da->file_exists(p)) {270return TTR("File does not exist.");271}272}273274if (r_path_valid) {275*r_path_valid = true;276}277278// Check file extension.279String extension = p.get_extension();280List<String> extensions;281282// Get all possible extensions for script.283for (int l = 0; l < language_menu->get_item_count(); l++) {284ScriptServer::get_language(l)->get_recognized_extensions(&extensions);285}286287bool found = false;288bool match = false;289for (const String &E : extensions) {290if (E.nocasecmp_to(extension) == 0) {291found = true;292if (E == ScriptServer::get_language(language_menu->get_selected())->get_extension()) {293match = true;294}295break;296}297}298299if (!found) {300return TTR("Invalid extension.");301}302if (!match) {303return TTR("Extension doesn't match chosen language.");304}305306// Let ScriptLanguage do custom validation.307return ScriptServer::get_language(language_menu->get_selected())->validate_path(p);308}309310void ScriptCreateDialog::_parent_name_changed(const String &p_parent) {311is_parent_name_valid = _validate_parent(parent_name->get_text());312validation_panel->update();313}314315void ScriptCreateDialog::_template_changed(int p_template) {316const ScriptLanguage::ScriptTemplate &sinfo = _get_current_template();317// Update last used dictionaries318if (is_using_templates && !parent_name->get_text().begins_with("\"res:")) {319if (sinfo.origin == ScriptLanguage::TemplateLocation::TEMPLATE_PROJECT) {320// Save the last used template for this node into the project dictionary.321Dictionary dic_templates_project = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());322dic_templates_project[parent_name->get_text()] = sinfo.get_hash();323EditorSettings::get_singleton()->set_project_metadata("script_setup", "templates_dictionary", dic_templates_project);324} else {325// Save template info to editor dictionary (not a project template).326Dictionary dic_templates = EDITOR_GET("_script_setup_templates_dictionary");327dic_templates[parent_name->get_text()] = sinfo.get_hash();328EditorSettings::get_singleton()->set("_script_setup_templates_dictionary", dic_templates);329// Remove template from project dictionary as we last used an editor level template.330Dictionary dic_templates_project = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());331if (dic_templates_project.has(parent_name->get_text())) {332dic_templates_project.erase(parent_name->get_text());333EditorSettings::get_singleton()->set_project_metadata("script_setup", "templates_dictionary", dic_templates_project);334}335}336}337338// Update template label information.339String template_info = U"• ";340template_info += TTR("Template:");341template_info += " " + sinfo.name;342if (!sinfo.description.is_empty()) {343template_info += " - " + sinfo.description;344}345validation_panel->set_message(MSG_ID_TEMPLATE, template_info, EditorValidationPanel::MSG_INFO, false);346}347348void ScriptCreateDialog::ok_pressed() {349if (is_new_script_created) {350_create_new();351if (_can_be_built_in()) {352// Only save state of built-in checkbox if it's enabled.353EditorSettings::get_singleton()->set_project_metadata("script_setup", "create_built_in_script", built_in->is_pressed());354}355} else {356_load_exist();357}358359EditorSettings::get_singleton()->save();360is_new_script_created = true;361validation_panel->update();362}363364void ScriptCreateDialog::_create_new() {365Ref<Script> scr;366367const ScriptLanguage::ScriptTemplate sinfo = _get_current_template();368369String parent_class = parent_name->get_text();370if (!parent_name->get_text().is_quoted() && !ClassDB::class_exists(parent_class) && !ScriptServer::is_global_class(parent_class)) {371// If base is a custom type, replace with script path instead.372const EditorData::CustomType *type = EditorNode::get_editor_data().get_custom_type_by_name(parent_class);373ERR_FAIL_NULL(type);374parent_class = "\"" + type->script->get_path() + "\"";375}376377String class_name = file_path->get_text().get_file().get_basename();378scr = ScriptServer::get_language(language_menu->get_selected())->make_template(sinfo.content, class_name, parent_class);379380if (is_built_in) {381scr->set_name(built_in_name->get_text());382// Make sure the script is compiled to make its type recognizable.383scr->reload();384} else {385String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());386scr->set_path(lpath);387Error err = ResourceSaver::save(scr, lpath, ResourceSaver::FLAG_CHANGE_PATH);388if (err != OK) {389alert->set_text(TTR("Error - Could not create script in filesystem."));390alert->popup_centered();391return;392}393}394395emit_signal(SNAME("script_created"), scr);396hide();397}398399void ScriptCreateDialog::_load_exist() {400String path = file_path->get_text();401Ref<Resource> p_script = ResourceLoader::load(path, "Script");402if (p_script.is_null()) {403alert->set_text(vformat(TTR("Error loading script from %s"), path));404alert->popup_centered();405return;406}407408emit_signal(SNAME("script_created"), p_script);409hide();410}411412void ScriptCreateDialog::_language_changed(int l) {413language = ScriptServer::get_language(l);414415can_inherit_from_file = language->can_inherit_from_file();416supports_built_in = language->supports_builtin_mode();417if (!supports_built_in) {418is_built_in = false;419}420421String path = file_path->get_text();422path = _adjust_file_path(path);423_path_changed(path);424file_path->set_text(path);425426EditorSettings::get_singleton()->set_project_metadata("script_setup", "last_selected_language", language_menu->get_item_text(language_menu->get_selected()));427428_parent_name_changed(parent_name->get_text());429validation_panel->update();430}431432void ScriptCreateDialog::_built_in_pressed() {433if (built_in->is_pressed()) {434is_built_in = true;435is_new_script_created = true;436} else {437is_built_in = false;438_path_changed(file_path->get_text());439}440validation_panel->update();441}442443void ScriptCreateDialog::_use_template_pressed() {444is_using_templates = use_templates->is_pressed();445EditorSettings::get_singleton()->set("_script_setup_use_script_templates", is_using_templates);446validation_panel->update();447}448449void ScriptCreateDialog::_browse_path(bool browse_parent, bool p_save) {450is_browsing_parent = browse_parent;451452if (p_save) {453file_browse->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);454file_browse->set_title(TTR("Open Script / Choose Location"));455file_browse->set_ok_button_text(TTR("Open"));456} else {457file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);458file_browse->set_title(TTR("Open Script"));459}460461file_browse->set_disable_overwrite_warning(true);462file_browse->clear_filters();463List<String> extensions;464465int lang = language_menu->get_selected();466ScriptServer::get_language(lang)->get_recognized_extensions(&extensions);467468for (const String &E : extensions) {469file_browse->add_filter("*." + E);470}471472file_browse->set_current_path(file_path->get_text());473file_browse->popup_file_dialog();474}475476void ScriptCreateDialog::_file_selected(const String &p_file) {477String path = ProjectSettings::get_singleton()->localize_path(p_file);478if (is_browsing_parent) {479parent_name->set_text("\"" + path + "\"");480_parent_name_changed(parent_name->get_text());481} else {482file_path->set_text(path);483_path_changed(path);484485String filename = path.get_file().get_basename();486int select_start = path.rfind(filename);487file_path->select(select_start, select_start + filename.length());488file_path->set_caret_column(select_start + filename.length());489file_path->grab_focus();490}491}492493void ScriptCreateDialog::_create() {494parent_name->set_text(select_class->get_selected_type().split(" ")[0]);495_parent_name_changed(parent_name->get_text());496}497498void ScriptCreateDialog::_browse_class_in_tree() {499select_class->set_base_type(base_type);500select_class->popup_create(true);501select_class->set_title(vformat(TTR("Inherit %s"), base_type));502select_class->set_ok_button_text(TTR("Inherit"));503}504505void ScriptCreateDialog::_path_changed(const String &p_path) {506if (is_built_in) {507return;508}509510is_new_script_created = true;511512path_error = _validate_path(p_path, false, &is_path_valid);513if (!path_error.is_empty()) {514validation_panel->update();515return;516}517518// Check if file exists.519Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);520String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges());521if (da->file_exists(p)) {522is_new_script_created = false;523}524validation_panel->update();525}526527void ScriptCreateDialog::_update_template_menu() {528bool is_language_using_templates = language->is_using_templates();529template_menu->set_disabled(false);530template_menu->clear();531template_list.clear();532533if (is_language_using_templates) {534// Get the latest templates used for each type of node from project settings then global settings.535Dictionary last_local_templates = EditorSettings::get_singleton()->get_project_metadata("script_setup", "templates_dictionary", Dictionary());536Dictionary last_global_templates = EDITOR_GET("_script_setup_templates_dictionary");537String inherits_base_type = parent_name->get_text();538539// If it inherits from a script, get its parent class first.540if (inherits_base_type[0] == '"') {541inherits_base_type = _get_parent_class_of_script(inherits_base_type.unquote());542}543544// Get all ancestor node for selected base node.545// There templates will also fit the base node.546Vector<String> hierarchy = _get_hierarchy(inherits_base_type);547int last_used_template = -1;548int preselected_template = -1;549int previous_ancestor_level = -1;550551// Templates can be stored in tree different locations.552Vector<ScriptLanguage::TemplateLocation> template_locations;553template_locations.append(ScriptLanguage::TEMPLATE_PROJECT);554template_locations.append(ScriptLanguage::TEMPLATE_EDITOR);555template_locations.append(ScriptLanguage::TEMPLATE_BUILT_IN);556557for (const ScriptLanguage::TemplateLocation &template_location : template_locations) {558String display_name = _get_script_origin_label(template_location);559bool separator = false;560int ancestor_level = 0;561for (const String ¤t_node : hierarchy) {562Vector<ScriptLanguage::ScriptTemplate> templates_found;563if (template_location == ScriptLanguage::TEMPLATE_BUILT_IN) {564templates_found = language->get_built_in_templates(current_node);565} else {566String template_directory;567if (template_location == ScriptLanguage::TEMPLATE_PROJECT) {568template_directory = EditorPaths::get_singleton()->get_project_script_templates_dir();569} else {570template_directory = EditorPaths::get_singleton()->get_script_templates_dir();571}572templates_found = _get_user_templates(language, current_node, template_directory, template_location);573}574if (!templates_found.is_empty()) {575if (!separator) {576template_menu->add_separator();577template_menu->set_item_text(-1, display_name);578template_menu->set_item_auto_translate_mode(-1, AUTO_TRANSLATE_MODE_ALWAYS);579separator = true;580}581for (ScriptLanguage::ScriptTemplate &t : templates_found) {582template_menu->add_item(t.inherit + ": " + t.name);583int id = template_menu->get_item_count() - 1;584// Check if this template should be preselected if node isn't in the last used dictionary.585if (ancestor_level < previous_ancestor_level || previous_ancestor_level == -1) {586previous_ancestor_level = ancestor_level;587preselected_template = id;588}589// Check for last used template for this node in project settings then in global settings.590if (last_local_templates.has(parent_name->get_text()) && t.get_hash() == String(last_local_templates[parent_name->get_text()])) {591last_used_template = id;592} 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()])) {593last_used_template = id;594}595t.id = id;596template_list.push_back(t);597String icon = has_theme_icon(t.inherit, EditorStringName(EditorIcons)) ? t.inherit : "Object";598template_menu->set_item_icon(id, get_editor_theme_icon(icon));599}600}601ancestor_level++;602}603}604605if (last_used_template != -1) {606template_menu->select(last_used_template);607} else if (preselected_template != -1) {608template_menu->select(preselected_template);609}610}611_template_changed(template_menu->get_selected());612}613614void ScriptCreateDialog::_update_dialog() {615// "Add Script Dialog" GUI logic and script checks.616_update_template_menu();617618// Is script path/name valid (order from top to bottom)?619620if (!is_built_in && !is_path_valid) {621validation_panel->set_message(MSG_ID_SCRIPT, TTR("Invalid path."), EditorValidationPanel::MSG_ERROR);622}623624if (!is_parent_name_valid && is_new_script_created) {625validation_panel->set_message(MSG_ID_SCRIPT, TTR("Invalid inherited parent name or path."), EditorValidationPanel::MSG_ERROR);626}627628if (validation_panel->is_valid() && !is_new_script_created) {629validation_panel->set_message(MSG_ID_SCRIPT, TTR("File exists, it will be reused."), EditorValidationPanel::MSG_OK);630}631632if (!is_built_in && !path_error.is_empty()) {633validation_panel->set_message(MSG_ID_PATH, path_error, EditorValidationPanel::MSG_ERROR);634}635636// Is script Built-in?637638if (is_built_in) {639file_path->set_editable(false);640path_button->set_disabled(true);641re_check_path = true;642} else {643file_path->set_editable(true);644path_button->set_disabled(false);645if (re_check_path) {646re_check_path = false;647_path_changed(file_path->get_text());648}649}650651if (!_can_be_built_in()) {652built_in->set_pressed(false);653}654built_in->set_disabled(!_can_be_built_in());655656// Is Script created or loaded from existing file?657658if (is_built_in) {659validation_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);660} else if (file_path->get_text().get_file().get_basename() == parent_name->get_text()) {661validation_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);662}663664path_controls[0]->set_visible(!is_built_in);665path_controls[1]->set_visible(!is_built_in);666name_controls[0]->set_visible(is_built_in);667name_controls[1]->set_visible(is_built_in);668669bool is_new_file = is_built_in || is_new_script_created;670671parent_name->set_editable(is_new_file);672parent_search_button->set_disabled(!is_new_file);673parent_browse_button->set_disabled(!is_new_file || !can_inherit_from_file);674template_inactive_message = "";675String button_text = is_new_file ? TTR("Create") : TTR("Load");676set_ok_button_text(button_text);677678if (is_new_file) {679if (is_built_in) {680validation_panel->set_message(MSG_ID_PATH, TTR("Built-in script (into scene file)."), EditorValidationPanel::MSG_OK);681}682} else {683template_inactive_message = TTRC("Using existing script file.");684if (load_enabled) {685if (is_path_valid) {686validation_panel->set_message(MSG_ID_PATH, TTR("Will load an existing script file."), EditorValidationPanel::MSG_OK);687}688} else {689validation_panel->set_message(MSG_ID_PATH, TTR("Script file already exists."), EditorValidationPanel::MSG_ERROR);690}691}692693// Show templates list if needed.694if (is_using_templates) {695// Check if at least one suitable template has been found.696if (template_menu->get_item_count() == 0 && template_inactive_message.is_empty()) {697template_inactive_message = TTRC("No suitable template.");698}699} else {700template_inactive_message = TTRC("Empty");701}702703if (!template_inactive_message.is_empty()) {704template_menu->set_disabled(true);705template_menu->clear();706template_menu->add_item(template_inactive_message);707template_menu->set_item_auto_translate_mode(-1, AUTO_TRANSLATE_MODE_ALWAYS);708validation_panel->set_message(MSG_ID_TEMPLATE, "", EditorValidationPanel::MSG_INFO);709}710}711712ScriptLanguage::ScriptTemplate ScriptCreateDialog::_get_current_template() const {713int selected_index = template_menu->get_selected();714for (const ScriptLanguage::ScriptTemplate &t : template_list) {715if (is_using_templates) {716if (t.id == selected_index) {717return t;718}719} else {720// Using empty built-in template if templates are disabled.721if (t.origin == ScriptLanguage::TemplateLocation::TEMPLATE_BUILT_IN && t.name == "Empty") {722return t;723}724}725}726return ScriptLanguage::ScriptTemplate();727}728729Vector<ScriptLanguage::ScriptTemplate> ScriptCreateDialog::_get_user_templates(const ScriptLanguage *p_language, const StringName &p_object, const String &p_dir, const ScriptLanguage::TemplateLocation &p_origin) const {730Vector<ScriptLanguage::ScriptTemplate> user_templates;731String extension = p_language->get_extension();732733String dir_path = p_dir.path_join(p_object);734735Ref<DirAccess> d = DirAccess::open(dir_path);736if (d.is_valid()) {737d->list_dir_begin();738String file = d->get_next();739while (file != String()) {740if (file.get_extension() == extension) {741user_templates.append(_parse_template(p_language, dir_path, file, p_origin, p_object));742}743file = d->get_next();744}745d->list_dir_end();746}747return user_templates;748}749750ScriptLanguage::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 {751ScriptLanguage::ScriptTemplate script_template = ScriptLanguage::ScriptTemplate();752script_template.origin = p_origin;753script_template.inherit = p_inherits;754int space_indent_size = 4;755// Get meta delimiter756String meta_delimiter;757for (const String &script_delimiter : p_language->get_comment_delimiters()) {758if (!script_delimiter.contains_char(' ')) {759meta_delimiter = script_delimiter;760break;761}762}763String meta_prefix = meta_delimiter + " meta-";764765// Parse file for meta-information and script content766Error err;767Ref<FileAccess> file = FileAccess::open(p_path.path_join(p_filename), FileAccess::READ, &err);768if (!err) {769while (!file->eof_reached()) {770String line = file->get_line();771if (line.begins_with(meta_prefix)) {772// Store meta information773line = line.substr(meta_prefix.length());774if (line.begins_with("name:")) {775script_template.name = line.substr(5).strip_edges();776} else if (line.begins_with("description:")) {777script_template.description = line.substr(12).strip_edges();778} else if (line.begins_with("space-indent:")) {779String indent_value = line.substr(13).strip_edges();780if (indent_value.is_valid_int()) {781int indent_size = indent_value.to_int();782if (indent_size >= 0) {783space_indent_size = indent_size;784} else {785WARN_PRINT(vformat("Template meta-space-indent need to be a non-negative integer value. Found %s.", indent_value));786}787} else {788WARN_PRINT(vformat("Template meta-space-indent need to be a valid integer value. Found %s.", indent_value));789}790}791} else {792// Replace indentation.793int i = 0;794int space_count = 0;795for (; i < line.length(); i++) {796if (line[i] == '\t') {797if (space_count) {798script_template.content += String(" ").repeat(space_count);799space_count = 0;800}801script_template.content += "_TS_";802} else if (line[i] == ' ') {803space_count++;804if (space_count == space_indent_size) {805script_template.content += "_TS_";806space_count = 0;807}808} else {809break;810}811}812if (space_count) {813script_template.content += String(" ").repeat(space_count);814}815script_template.content += line.substr(i) + "\n";816}817}818}819820script_template.content = script_template.content.lstrip("\n");821822// Get name from file name if no name in meta information823if (script_template.name == String()) {824script_template.name = p_filename.get_basename().capitalize();825}826827return script_template;828}829830String ScriptCreateDialog::_get_script_origin_label(const ScriptLanguage::TemplateLocation &p_origin) const {831switch (p_origin) {832case ScriptLanguage::TEMPLATE_BUILT_IN:833return TTRC("Built-in");834case ScriptLanguage::TEMPLATE_EDITOR:835return TTRC("Editor");836case ScriptLanguage::TEMPLATE_PROJECT:837return TTRC("Project");838}839return "";840}841842void ScriptCreateDialog::_bind_methods() {843ClassDB::bind_method(D_METHOD("config", "inherits", "path", "built_in_enabled", "load_enabled"), &ScriptCreateDialog::config, DEFVAL(true), DEFVAL(true));844845ADD_SIGNAL(MethodInfo("script_created", PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script")));846}847848ScriptCreateDialog::ScriptCreateDialog() {849if (EditorSettings::get_singleton()) {850EDITOR_DEF("_script_setup_templates_dictionary", Dictionary());851}852853/* Main Controls */854855GridContainer *gc = memnew(GridContainer);856gc->set_columns(2);857858/* Information Messages Field */859860validation_panel = memnew(EditorValidationPanel);861validation_panel->add_line(MSG_ID_SCRIPT, TTR("Script path/name is valid."));862validation_panel->add_line(MSG_ID_PATH, TTR("Will create a new script file."));863validation_panel->add_line(MSG_ID_BUILT_IN);864validation_panel->add_line(MSG_ID_TEMPLATE);865validation_panel->set_update_callback(callable_mp(this, &ScriptCreateDialog::_update_dialog));866validation_panel->set_accept_button(get_ok_button());867868/* Spacing */869870Control *spacing = memnew(Control);871spacing->set_custom_minimum_size(Size2(0, 10 * EDSCALE));872873VBoxContainer *vb = memnew(VBoxContainer);874vb->add_child(gc);875vb->add_child(spacing);876vb->add_child(validation_panel);877add_child(vb);878879/* Language */880881language_menu = memnew(OptionButton);882language_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);883language_menu->set_custom_minimum_size(Size2(350, 0) * EDSCALE);884language_menu->set_expand_icon(true);885language_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);886language_menu->set_accessibility_name(TTRC("Language:"));887gc->add_child(memnew(Label(TTR("Language:"))));888gc->add_child(language_menu);889890default_language = -1;891for (int i = 0; i < ScriptServer::get_language_count(); i++) {892String lang = ScriptServer::get_language(i)->get_name();893language_menu->add_item(lang);894if (lang == "GDScript") {895default_language = i;896}897}898if (default_language >= 0) {899language_menu->select(default_language);900}901902language_menu->connect(SceneStringName(item_selected), callable_mp(this, &ScriptCreateDialog::_language_changed));903904/* Inherits */905906base_type = "Object";907908HBoxContainer *hb = memnew(HBoxContainer);909hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);910parent_name = memnew(LineEdit);911parent_name->set_accessibility_name(TTRC("Parent Name"));912parent_name->connect(SceneStringName(text_changed), callable_mp(this, &ScriptCreateDialog::_parent_name_changed));913parent_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);914hb->add_child(parent_name);915register_text_enter(parent_name);916parent_search_button = memnew(Button);917parent_search_button->set_accessibility_name(TTRC("Search Parent"));918parent_search_button->connect(SceneStringName(pressed), callable_mp(this, &ScriptCreateDialog::_browse_class_in_tree));919hb->add_child(parent_search_button);920parent_browse_button = memnew(Button);921parent_browse_button->set_accessibility_name(TTRC("Select Parent"));922parent_browse_button->connect(SceneStringName(pressed), callable_mp(this, &ScriptCreateDialog::_browse_path).bind(true, false));923hb->add_child(parent_browse_button);924gc->add_child(memnew(Label(TTR("Inherits:"))));925gc->add_child(hb);926927/* Templates */928gc->add_child(memnew(Label(TTR("Template:"))));929HBoxContainer *template_hb = memnew(HBoxContainer);930template_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);931932use_templates = memnew(CheckBox);933use_templates->set_pressed(is_using_templates);934use_templates->set_accessibility_name(TTRC("Use Template"));935use_templates->connect(SceneStringName(pressed), callable_mp(this, &ScriptCreateDialog::_use_template_pressed));936template_hb->add_child(use_templates);937938template_inactive_message = "";939940template_menu = memnew(OptionButton);941template_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);942template_menu->set_accessibility_name(TTRC("Template"));943template_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);944template_menu->connect(SceneStringName(item_selected), callable_mp(this, &ScriptCreateDialog::_template_changed));945template_hb->add_child(template_menu);946947gc->add_child(template_hb);948949/* Built-in Script */950951built_in = memnew(CheckBox);952built_in->set_text(TTR("On"));953built_in->set_accessibility_name(TTRC("Built-in Script:"));954built_in->connect(SceneStringName(pressed), callable_mp(this, &ScriptCreateDialog::_built_in_pressed));955gc->add_child(memnew(Label(TTR("Built-in Script:"))));956gc->add_child(built_in);957958/* Path */959960hb = memnew(HBoxContainer);961hb->connect(SceneStringName(sort_children), callable_mp(this, &ScriptCreateDialog::_path_hbox_sorted));962file_path = memnew(LineEdit);963file_path->set_accessibility_name(TTRC("Path:"));964file_path->connect(SceneStringName(text_changed), callable_mp(this, &ScriptCreateDialog::_path_changed));965file_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);966hb->add_child(file_path);967register_text_enter(file_path);968path_button = memnew(Button);969path_button->set_accessibility_name(TTRC("Select File"));970path_button->connect(SceneStringName(pressed), callable_mp(this, &ScriptCreateDialog::_browse_path).bind(false, true));971hb->add_child(path_button);972Label *label = memnew(Label(TTR("Path:")));973gc->add_child(label);974gc->add_child(hb);975path_controls[0] = label;976path_controls[1] = hb;977978/* Name */979980built_in_name = memnew(LineEdit);981built_in_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);982built_in_name->set_accessibility_name(TTRC("Name:"));983register_text_enter(built_in_name);984label = memnew(Label(TTR("Name:")));985gc->add_child(label);986gc->add_child(built_in_name);987name_controls[0] = label;988name_controls[1] = built_in_name;989label->hide();990built_in_name->hide();991992/* Dialog Setup */993994select_class = memnew(CreateDialog);995select_class->connect("create", callable_mp(this, &ScriptCreateDialog::_create));996select_class->for_inherit();997add_child(select_class);998999file_browse = memnew(EditorFileDialog);1000file_browse->connect("file_selected", callable_mp(this, &ScriptCreateDialog::_file_selected));1001file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);1002add_child(file_browse);1003set_ok_button_text(TTR("Create"));1004alert = memnew(AcceptDialog);1005alert->get_label()->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);1006alert->get_label()->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);1007alert->get_label()->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);1008alert->get_label()->set_custom_minimum_size(Size2(325, 60) * EDSCALE);1009add_child(alert);10101011set_hide_on_ok(false);1012set_title(TTR("Attach Node Script"));1013}101410151016