Debian Codegraph @

editor/script/script_create_dialog.cpp

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