Debian Codegraph @

editor/script/script_editor_plugin.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* script_editor_plugin.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_editor_plugin.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/input/input.h"
35 #include "core/io/config_file.h"
36 #include "core/io/file_access.h"
37 #include "core/io/json.h"
38 #include "core/io/resource_loader.h"
39 #include "core/os/keyboard.h"
40 #include "core/os/os.h"
41 #include "core/string/fuzzy_search.h"
42 #include "core/version.h"
43 #include "editor/debugger/editor_debugger_node.h"
44 #include "editor/debugger/script_editor_debugger.h"
45 #include "editor/doc/editor_help_search.h"
46 #include "editor/docks/editor_dock_manager.h"
47 #include "editor/docks/filesystem_dock.h"
48 #include "editor/docks/inspector_dock.h"
49 #include "editor/docks/signals_dock.h"
50 #include "editor/editor_interface.h"
51 #include "editor/editor_main_screen.h"
52 #include "editor/editor_node.h"
53 #include "editor/editor_string_names.h"
54 #include "editor/file_system/editor_paths.h"
55 #include "editor/gui/code_editor.h"
56 #include "editor/gui/editor_file_dialog.h"
57 #include "editor/gui/editor_toaster.h"
58 #include "editor/gui/window_wrapper.h"
59 #include "editor/inspector/editor_context_menu_plugin.h"
60 #include "editor/run/editor_run_bar.h"
61 #include "editor/scene/editor_scene_tabs.h"
62 #include "editor/script/editor_script.h"
63 #include "editor/script/find_in_files.h"
64 #include "editor/settings/editor_command_palette.h"
65 #include "editor/settings/editor_settings.h"
66 #include "editor/shader/shader_editor_plugin.h"
67 #include "editor/shader/text_shader_editor.h"
68 #include "editor/themes/editor_scale.h"
69 #include "editor/themes/editor_theme_manager.h"
70 #include "scene/gui/separator.h"
71 #include "scene/gui/tab_container.h"
72 #include "scene/gui/texture_rect.h"
73 #include "scene/main/node.h"
74 #include "scene/main/window.h"
75 #include "script_text_editor.h"
76 #include "servers/display/display_server.h"
77 #include "text_editor.h"
78
79 /*** SYNTAX HIGHLIGHTER ****/
80
81 String EditorSyntaxHighlighter::_get_name() const {
82 String ret = "Unnamed";
83 GDVIRTUAL_CALL(_get_name, ret);
84 return ret;
85 }
86
87 PackedStringArray EditorSyntaxHighlighter::_get_supported_languages() const {
88 PackedStringArray ret;
89 GDVIRTUAL_CALL(_get_supported_languages, ret);
90 return ret;
91 }
92
93 Ref<EditorSyntaxHighlighter> EditorSyntaxHighlighter::_create() const {
94 Ref<EditorSyntaxHighlighter> syntax_highlighter;
95 if (GDVIRTUAL_IS_OVERRIDDEN(_create)) {
96 GDVIRTUAL_CALL(_create, syntax_highlighter);
97 } else {
98 syntax_highlighter.instantiate();
99 if (get_script_instance()) {
100 syntax_highlighter->set_script(get_script_instance()->get_script());
101 }
102 }
103 return syntax_highlighter;
104 }
105
106 void EditorSyntaxHighlighter::_bind_methods() {
107 ClassDB::bind_method(D_METHOD("_get_edited_resource"), &EditorSyntaxHighlighter::_get_edited_resource);
108
109 GDVIRTUAL_BIND(_get_name)
110 GDVIRTUAL_BIND(_get_supported_languages)
111 GDVIRTUAL_BIND(_create)
112 }
113
114 ////
115
116 void EditorStandardSyntaxHighlighter::_update_cache() {
117 highlighter->set_text_edit(text_edit);
118 highlighter->clear_keyword_colors();
119 highlighter->clear_member_keyword_colors();
120 highlighter->clear_color_regions();
121
122 highlighter->set_symbol_color(EDITOR_GET("text_editor/theme/highlighting/symbol_color"));
123 highlighter->set_function_color(EDITOR_GET("text_editor/theme/highlighting/function_color"));
124 highlighter->set_number_color(EDITOR_GET("text_editor/theme/highlighting/number_color"));
125 highlighter->set_member_variable_color(EDITOR_GET("text_editor/theme/highlighting/member_variable_color"));
126
127 /* Engine types. */
128 const Color type_color = EDITOR_GET("text_editor/theme/highlighting/engine_type_color");
129 LocalVector<StringName> types;
130 ClassDB::get_class_list(types);
131 for (const StringName &type : types) {
132 highlighter->add_keyword_color(type, type_color);
133 }
134
135 /* User types. */
136 const Color usertype_color = EDITOR_GET("text_editor/theme/highlighting/user_type_color");
137 LocalVector<StringName> global_classes;
138 ScriptServer::get_global_class_list(global_classes);
139 for (const StringName &class_name : global_classes) {
140 highlighter->add_keyword_color(class_name, usertype_color);
141 }
142
143 /* Autoloads. */
144 HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
145 for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
146 const ProjectSettings::AutoloadInfo &info = E.value;
147 if (info.is_singleton) {
148 highlighter->add_keyword_color(info.name, usertype_color);
149 }
150 }
151
152 const ScriptLanguage *scr_lang = script_language;
153 StringName instance_base;
154
155 if (scr_lang == nullptr) {
156 const Ref<Script> scr = _get_edited_resource();
157 if (scr.is_valid()) {
158 scr_lang = scr->get_language();
159 instance_base = scr->get_instance_base_type();
160 }
161 }
162
163 if (scr_lang != nullptr) {
164 /* Core types. */
165 const Color basetype_color = EDITOR_GET("text_editor/theme/highlighting/base_type_color");
166 List<String> core_types;
167 scr_lang->get_core_type_words(&core_types);
168 for (const String &E : core_types) {
169 highlighter->add_keyword_color(E, basetype_color);
170 }
171
172 /* Reserved words. */
173 const Color keyword_color = EDITOR_GET("text_editor/theme/highlighting/keyword_color");
174 const Color control_flow_keyword_color = EDITOR_GET("text_editor/theme/highlighting/control_flow_keyword_color");
175 for (const String &keyword : scr_lang->get_reserved_words()) {
176 if (scr_lang->is_control_flow_keyword(keyword)) {
177 highlighter->add_keyword_color(keyword, control_flow_keyword_color);
178 } else {
179 highlighter->add_keyword_color(keyword, keyword_color);
180 }
181 }
182
183 /* Member types. */
184 const Color member_variable_color = EDITOR_GET("text_editor/theme/highlighting/member_variable_color");
185 if (instance_base != StringName()) {
186 List<PropertyInfo> plist;
187 ClassDB::get_property_list(instance_base, &plist);
188 for (const PropertyInfo &E : plist) {
189 String prop_name = E.name;
190 if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) {
191 continue;
192 }
193 if (prop_name.contains_char('/')) {
194 continue;
195 }
196 highlighter->add_member_keyword_color(prop_name, member_variable_color);
197 }
198
199 List<String> clist;
200 ClassDB::get_integer_constant_list(instance_base, &clist);
201 for (const String &E : clist) {
202 highlighter->add_member_keyword_color(E, member_variable_color);
203 }
204 }
205
206 /* Comments */
207 const Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color");
208 for (const String &comment : scr_lang->get_comment_delimiters()) {
209 String beg = comment.get_slicec(' ', 0);
210 String end = comment.get_slice_count(" ") > 1 ? comment.get_slicec(' ', 1) : String();
211 highlighter->add_color_region(beg, end, comment_color, end.is_empty());
212 }
213
214 /* Doc comments */
215 const Color doc_comment_color = EDITOR_GET("text_editor/theme/highlighting/doc_comment_color");
216 for (const String &doc_comment : scr_lang->get_doc_comment_delimiters()) {
217 String beg = doc_comment.get_slicec(' ', 0);
218 String end = doc_comment.get_slice_count(" ") > 1 ? doc_comment.get_slicec(' ', 1) : String();
219 highlighter->add_color_region(beg, end, doc_comment_color, end.is_empty());
220 }
221
222 /* Strings */
223 const Color string_color = EDITOR_GET("text_editor/theme/highlighting/string_color");
224 for (const String &string : scr_lang->get_string_delimiters()) {
225 String beg = string.get_slicec(' ', 0);
226 String end = string.get_slice_count(" ") > 1 ? string.get_slicec(' ', 1) : String();
227 highlighter->add_color_region(beg, end, string_color, end.is_empty());
228 }
229 }
230 }
231
232 Ref<EditorSyntaxHighlighter> EditorStandardSyntaxHighlighter::_create() const {
233 Ref<EditorStandardSyntaxHighlighter> syntax_highlighter;
234 syntax_highlighter.instantiate();
235 return syntax_highlighter;
236 }
237
238 ////
239
240 Ref<EditorSyntaxHighlighter> EditorPlainTextSyntaxHighlighter::_create() const {
241 Ref<EditorPlainTextSyntaxHighlighter> syntax_highlighter;
242 syntax_highlighter.instantiate();
243 return syntax_highlighter;
244 }
245
246 ////
247
248 void EditorJSONSyntaxHighlighter::_update_cache() {
249 highlighter->set_text_edit(text_edit);
250 highlighter->clear_keyword_colors();
251 highlighter->clear_member_keyword_colors();
252 highlighter->clear_color_regions();
253
254 highlighter->set_symbol_color(EDITOR_GET("text_editor/theme/highlighting/symbol_color"));
255 highlighter->set_number_color(EDITOR_GET("text_editor/theme/highlighting/number_color"));
256
257 const Color string_color = EDITOR_GET("text_editor/theme/highlighting/string_color");
258 highlighter->add_color_region("\"", "\"", string_color);
259 }
260
261 Ref<EditorSyntaxHighlighter> EditorJSONSyntaxHighlighter::_create() const {
262 Ref<EditorJSONSyntaxHighlighter> syntax_highlighter;
263 syntax_highlighter.instantiate();
264 return syntax_highlighter;
265 }
266
267 ////
268
269 void EditorMarkdownSyntaxHighlighter::_update_cache() {
270 highlighter->set_text_edit(text_edit);
271 highlighter->clear_keyword_colors();
272 highlighter->clear_member_keyword_colors();
273 highlighter->clear_color_regions();
274
275 // Disable automatic symbolic highlights, as these don't make sense for prose.
276 highlighter->set_symbol_color(EDITOR_GET("text_editor/theme/highlighting/text_color"));
277 highlighter->set_number_color(EDITOR_GET("text_editor/theme/highlighting/text_color"));
278 highlighter->set_member_variable_color(EDITOR_GET("text_editor/theme/highlighting/text_color"));
279 highlighter->set_function_color(EDITOR_GET("text_editor/theme/highlighting/text_color"));
280
281 // Headings (any level).
282 const Color function_color = EDITOR_GET("text_editor/theme/highlighting/function_color");
283 highlighter->add_color_region("#", "", function_color);
284
285 // Bold.
286 highlighter->add_color_region("**", "**", function_color);
287 // `__bold__` syntax is not supported as color regions must begin with a symbol,
288 // not a character that is valid in an identifier.
289
290 // Code (both inline code and triple-backticks code blocks).
291 const Color code_color = EDITOR_GET("text_editor/theme/highlighting/engine_type_color");
292 highlighter->add_color_region("`", "`", code_color);
293
294 // Link (both references and inline links with URLs). The URL is not highlighted.
295 const Color link_color = EDITOR_GET("text_editor/theme/highlighting/keyword_color");
296 highlighter->add_color_region("[", "]", link_color);
297
298 // Quote.
299 const Color quote_color = EDITOR_GET("text_editor/theme/highlighting/string_color");
300 highlighter->add_color_region(">", "", quote_color, true);
301
302 // HTML comment, which is also supported in Markdown.
303 const Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color");
304 highlighter->add_color_region("<!--", "-->", comment_color);
305 }
306
307 Ref<EditorSyntaxHighlighter> EditorMarkdownSyntaxHighlighter::_create() const {
308 Ref<EditorMarkdownSyntaxHighlighter> syntax_highlighter;
309 syntax_highlighter.instantiate();
310 return syntax_highlighter;
311 }
312
313 ///
314
315 void EditorConfigFileSyntaxHighlighter::_update_cache() {
316 highlighter->set_text_edit(text_edit);
317 highlighter->clear_keyword_colors();
318 highlighter->clear_member_keyword_colors();
319 highlighter->clear_color_regions();
320
321 highlighter->set_symbol_color(EDITOR_GET("text_editor/theme/highlighting/symbol_color"));
322 highlighter->set_number_color(EDITOR_GET("text_editor/theme/highlighting/number_color"));
323 // Assume that all function-style syntax is for types such as `Vector2()` and `PackedStringArray()`.
324 highlighter->set_function_color(EDITOR_GET("text_editor/theme/highlighting/base_type_color"));
325
326 // Disable member variable highlighting as it's not relevant for ConfigFile.
327 highlighter->set_member_variable_color(EDITOR_GET("text_editor/theme/highlighting/text_color"));
328
329 const Color string_color = EDITOR_GET("text_editor/theme/highlighting/string_color");
330 highlighter->add_color_region("\"", "\"", string_color);
331
332 // FIXME: Sections in ConfigFile must be at the beginning of a line. Otherwise, it can be an array within a line.
333 const Color function_color = EDITOR_GET("text_editor/theme/highlighting/function_color");
334 highlighter->add_color_region("[", "]", function_color);
335
336 const Color keyword_color = EDITOR_GET("text_editor/theme/highlighting/keyword_color");
337 highlighter->add_keyword_color("true", keyword_color);
338 highlighter->add_keyword_color("false", keyword_color);
339 highlighter->add_keyword_color("null", keyword_color);
340 highlighter->add_keyword_color("ExtResource", keyword_color);
341 highlighter->add_keyword_color("SubResource", keyword_color);
342
343 const Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color");
344 highlighter->add_color_region(";", "", comment_color);
345 }
346
347 Ref<EditorSyntaxHighlighter> EditorConfigFileSyntaxHighlighter::_create() const {
348 Ref<EditorConfigFileSyntaxHighlighter> syntax_highlighter;
349 syntax_highlighter.instantiate();
350 return syntax_highlighter;
351 }
352
353 ////////////////////////////////////////////////////////////////////////////////
354
355 /*** SCRIPT EDITOR ****/
356
357 void ScriptEditorBase::_bind_methods() {
358 ClassDB::bind_method(D_METHOD("get_base_editor"), &ScriptEditorBase::get_base_editor);
359 ClassDB::bind_method(D_METHOD("add_syntax_highlighter", "highlighter"), &ScriptEditorBase::add_syntax_highlighter);
360
361 ADD_SIGNAL(MethodInfo("name_changed"));
362 ADD_SIGNAL(MethodInfo("edited_script_changed"));
363 ADD_SIGNAL(MethodInfo("request_help", PropertyInfo(Variant::STRING, "topic")));
364 ADD_SIGNAL(MethodInfo("request_open_script_at_line", PropertyInfo(Variant::OBJECT, "script"), PropertyInfo(Variant::INT, "line")));
365 ADD_SIGNAL(MethodInfo("request_save_history"));
366 ADD_SIGNAL(MethodInfo("request_save_previous_state", PropertyInfo(Variant::DICTIONARY, "state")));
367 ADD_SIGNAL(MethodInfo("go_to_help", PropertyInfo(Variant::STRING, "what")));
368 ADD_SIGNAL(MethodInfo("search_in_files_requested", PropertyInfo(Variant::STRING, "text")));
369 ADD_SIGNAL(MethodInfo("replace_in_files_requested", PropertyInfo(Variant::STRING, "text")));
370 ADD_SIGNAL(MethodInfo("go_to_method", PropertyInfo(Variant::OBJECT, "script"), PropertyInfo(Variant::STRING, "method")));
371 }
372
373 void ScriptEditorQuickOpen::popup_dialog(const Vector<String> &p_functions, bool p_dontclear) {
374 popup_centered_ratio(0.6);
375 if (p_dontclear) {
376 search_box->select_all();
377 } else {
378 search_box->clear();
379 }
380 search_box->grab_focus();
381 functions = p_functions;
382 _update_search();
383 }
384
385 void ScriptEditorQuickOpen::_text_changed(const String &p_newtext) {
386 _update_search();
387 }
388
389 void ScriptEditorQuickOpen::_sbox_input(const Ref<InputEvent> &p_event) {
390 // Redirect navigational key events to the tree.
391 Ref<InputEventKey> key = p_event;
392 if (key.is_valid()) {
393 if (key->is_action("ui_up", true) || key->is_action("ui_down", true) || key->is_action("ui_page_up") || key->is_action("ui_page_down")) {
394 search_options->gui_input(key);
395 search_box->accept_event();
396 }
397 }
398 }
399
400 void ScriptEditorQuickOpen::_update_search() {
401 search_options->clear();
402 TreeItem *root = search_options->create_item();
403
404 for (int i = 0; i < functions.size(); i++) {
405 String file = functions[i];
406 if ((search_box->get_text().is_empty() || file.containsn(search_box->get_text()))) {
407 TreeItem *ti = search_options->create_item(root);
408 ti->set_text(0, file);
409 if (root->get_first_child() == ti) {
410 ti->select(0);
411 }
412 }
413 }
414
415 get_ok_button()->set_disabled(root->get_first_child() == nullptr);
416 }
417
418 void ScriptEditorQuickOpen::_confirmed() {
419 TreeItem *ti = search_options->get_selected();
420 if (!ti) {
421 return;
422 }
423 int line = ti->get_text(0).get_slicec(':', 1).to_int();
424
425 emit_signal(SNAME("goto_line"), line - 1);
426 hide();
427 }
428
429 void ScriptEditorQuickOpen::_notification(int p_what) {
430 switch (p_what) {
431 case NOTIFICATION_ENTER_TREE: {
432 connect(SceneStringName(confirmed), callable_mp(this, &ScriptEditorQuickOpen::_confirmed));
433
434 search_box->set_clear_button_enabled(true);
435 [[fallthrough]];
436 }
437 case NOTIFICATION_VISIBILITY_CHANGED: {
438 search_box->set_right_icon(search_options->get_editor_theme_icon(SNAME("Search")));
439 } break;
440
441 case NOTIFICATION_EXIT_TREE: {
442 disconnect(SceneStringName(confirmed), callable_mp(this, &ScriptEditorQuickOpen::_confirmed));
443 } break;
444 }
445 }
446
447 void ScriptEditorQuickOpen::_bind_methods() {
448 ADD_SIGNAL(MethodInfo("goto_line", PropertyInfo(Variant::INT, "line")));
449 }
450
451 ScriptEditorQuickOpen::ScriptEditorQuickOpen() {
452 VBoxContainer *vbc = memnew(VBoxContainer);
453 add_child(vbc);
454 search_box = memnew(LineEdit);
455 vbc->add_margin_child(TTRC("Search:"), search_box);
456 search_box->connect(SceneStringName(text_changed), callable_mp(this, &ScriptEditorQuickOpen::_text_changed));
457 search_box->connect(SceneStringName(gui_input), callable_mp(this, &ScriptEditorQuickOpen::_sbox_input));
458 search_options = memnew(Tree);
459 vbc->add_margin_child(TTRC("Matches:"), search_options, true);
460 set_ok_button_text(TTRC("Open"));
461 get_ok_button()->set_disabled(true);
462 register_text_enter(search_box);
463 set_hide_on_ok(false);
464 search_options->connect("item_activated", callable_mp(this, &ScriptEditorQuickOpen::_confirmed));
465 search_options->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
466 search_options->set_hide_root(true);
467 search_options->set_hide_folding(true);
468 search_options->add_theme_constant_override("draw_guides", 1);
469 }
470
471 /////////////////////////////////
472
473 ScriptEditor *ScriptEditor::script_editor = nullptr;
474
475 /*** SCRIPT EDITOR ******/
476
477 String ScriptEditor::_get_debug_tooltip(const String &p_text, Node *p_se) {
478 if (EDITOR_GET("text_editor/behavior/documentation/enable_tooltips")) {
479 return String();
480 }
481
482 // NOTE: See also `ScriptTextEditor::_show_symbol_tooltip()` for documentation tooltips enabled.
483 String debug_value = EditorDebuggerNode::get_singleton()->get_var_value(p_text);
484 if (!debug_value.is_empty()) {
485 constexpr int DISPLAY_LIMIT = 1024;
486 if (debug_value.size() > DISPLAY_LIMIT) {
487 debug_value = debug_value.left(DISPLAY_LIMIT) + "... " + TTR("(truncated)");
488 }
489 debug_value = TTR("Current value: ") + debug_value;
490 }
491
492 return debug_value;
493 }
494
495 void ScriptEditor::_breaked(bool p_breaked, bool p_can_debug) {
496 if (external_editor_active) {
497 return;
498 }
499
500 for (int i = 0; i < tab_container->get_tab_count(); i++) {
501 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
502 if (!se) {
503 continue;
504 }
505
506 se->set_debugger_active(p_breaked);
507 }
508 }
509
510 void ScriptEditor::_script_created(Ref<Script> p_script) {
511 EditorNode::get_singleton()->push_item(p_script.operator->());
512 }
513
514 void ScriptEditor::_goto_script_line2(int p_line) {
515 ScriptEditorBase *current = _get_current_editor();
516 if (current) {
517 current->goto_line(p_line);
518 }
519 }
520
521 void ScriptEditor::_goto_script_line(Ref<RefCounted> p_script, int p_line) {
522 Ref<Script> scr = Object::cast_to<Script>(*p_script);
523 if (scr.is_valid() && (scr->has_source_code() || scr->get_path().is_resource_file())) {
524 if (edit(p_script, p_line, 0)) {
525 EditorNode::get_singleton()->push_item(p_script.ptr());
526
527 ScriptEditorBase *current = _get_current_editor();
528 if (ScriptTextEditor *script_text_editor = Object::cast_to<ScriptTextEditor>(current)) {
529 script_text_editor->goto_line_centered(p_line);
530 } else if (current) {
531 current->goto_line(p_line);
532 }
533
534 _save_history();
535 }
536 }
537 }
538
539 void ScriptEditor::_set_execution(Ref<RefCounted> p_script, int p_line) {
540 Ref<Script> scr = Object::cast_to<Script>(*p_script);
541 if (scr.is_valid() && (scr->has_source_code() || scr->get_path().is_resource_file())) {
542 for (int i = 0; i < tab_container->get_tab_count(); i++) {
543 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
544 if (!se) {
545 continue;
546 }
547
548 if ((scr.is_valid() && se->get_edited_resource() == p_script) || se->get_edited_resource()->get_path() == scr->get_path()) {
549 se->set_executing_line(p_line);
550 }
551 }
552 }
553 }
554
555 void ScriptEditor::_clear_execution(Ref<RefCounted> p_script) {
556 Ref<Script> scr = Object::cast_to<Script>(*p_script);
557 if (scr.is_valid() && (scr->has_source_code() || scr->get_path().is_resource_file())) {
558 for (int i = 0; i < tab_container->get_tab_count(); i++) {
559 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
560 if (!se) {
561 continue;
562 }
563
564 if ((scr.is_valid() && se->get_edited_resource() == p_script) || se->get_edited_resource()->get_path() == scr->get_path()) {
565 se->clear_executing_line();
566 }
567 }
568 }
569 }
570
571 void ScriptEditor::_set_breakpoint(Ref<RefCounted> p_script, int p_line, bool p_enabled) {
572 Ref<Script> scr = Object::cast_to<Script>(*p_script);
573 if (scr.is_valid() && (scr->has_source_code() || scr->get_path().is_resource_file())) {
574 // Update if open.
575 for (int i = 0; i < tab_container->get_tab_count(); i++) {
576 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
577 if (se && se->get_edited_resource()->get_path() == scr->get_path()) {
578 se->set_breakpoint(p_line, p_enabled);
579 return;
580 }
581 }
582
583 // Handle closed.
584 Dictionary state = script_editor_cache->get_value(scr->get_path(), "state");
585 Array breakpoints;
586 if (state.has("breakpoints")) {
587 breakpoints = state["breakpoints"];
588 }
589
590 if (breakpoints.has(p_line)) {
591 if (!p_enabled) {
592 breakpoints.erase(p_line);
593 }
594 } else if (p_enabled) {
595 breakpoints.push_back(p_line);
596 }
597 state["breakpoints"] = breakpoints;
598 script_editor_cache->set_value(scr->get_path(), "state", state);
599 EditorDebuggerNode::get_singleton()->set_breakpoint(scr->get_path(), p_line + 1, p_enabled);
600 }
601 }
602
603 void ScriptEditor::_clear_breakpoints() {
604 for (int i = 0; i < tab_container->get_tab_count(); i++) {
605 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
606 if (se) {
607 se->clear_breakpoints();
608 }
609 }
610
611 // Clear from closed scripts.
612 Vector<String> cached_editors = script_editor_cache->get_sections();
613 for (const String &E : cached_editors) {
614 Array breakpoints = _get_cached_breakpoints_for_script(E);
615 for (int breakpoint : breakpoints) {
616 EditorDebuggerNode::get_singleton()->set_breakpoint(E, (int)breakpoint + 1, false);
617 }
618
619 if (breakpoints.size() > 0) {
620 Dictionary state = script_editor_cache->get_value(E, "state");
621 state["breakpoints"] = Array();
622 script_editor_cache->set_value(E, "state", state);
623 }
624 }
625 }
626
627 Array ScriptEditor::_get_cached_breakpoints_for_script(const String &p_path) const {
628 if (!ResourceLoader::exists(p_path, "Script") || p_path.begins_with("local://") || !script_editor_cache->has_section_key(p_path, "state")) {
629 return Array();
630 }
631
632 Dictionary state = script_editor_cache->get_value(p_path, "state");
633 if (!state.has("breakpoints")) {
634 return Array();
635 }
636 return state["breakpoints"];
637 }
638
639 ScriptEditorBase *ScriptEditor::_get_current_editor() const {
640 int selected = tab_container->get_current_tab();
641 if (selected < 0 || selected >= tab_container->get_tab_count()) {
642 return nullptr;
643 }
644
645 return Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(selected));
646 }
647
648 void ScriptEditor::_update_history_arrows() {
649 script_back->set_disabled(history_pos <= 0);
650 script_forward->set_disabled(history_pos >= history.size() - 1);
651 }
652
653 void ScriptEditor::_save_history() {
654 if (history_pos >= 0 && history_pos < history.size() && history[history_pos].control == tab_container->get_current_tab_control()) {
655 Node *n = tab_container->get_current_tab_control();
656
657 if (Object::cast_to<ScriptEditorBase>(n)) {
658 history.write[history_pos].state = Object::cast_to<ScriptEditorBase>(n)->get_navigation_state();
659 }
660 if (Object::cast_to<EditorHelp>(n)) {
661 history.write[history_pos].state = Object::cast_to<EditorHelp>(n)->get_scroll();
662 }
663 }
664
665 history.resize(history_pos + 1);
666 ScriptHistory sh;
667 sh.control = tab_container->get_current_tab_control();
668 sh.state = Variant();
669
670 history.push_back(sh);
671 history_pos++;
672
673 _update_history_arrows();
674 }
675
676 void ScriptEditor::_save_previous_state(Dictionary p_state) {
677 if (lock_history) {
678 // Done as a result of a deferred call triggered by set_edit_state().
679 return;
680 }
681
682 if (history_pos >= 0 && history_pos < history.size() && history[history_pos].control == tab_container->get_current_tab_control()) {
683 Node *n = tab_container->get_current_tab_control();
684
685 if (Object::cast_to<ScriptTextEditor>(n)) {
686 history.write[history_pos].state = p_state;
687 }
688 }
689
690 history.resize(history_pos + 1);
691 ScriptHistory sh;
692 sh.control = tab_container->get_current_tab_control();
693 sh.state = Variant();
694
695 history.push_back(sh);
696 history_pos++;
697
698 _update_history_arrows();
699 }
700
701 void ScriptEditor::_go_to_tab(int p_idx) {
702 ScriptEditorBase *current = _get_current_editor();
703 if (current) {
704 if (current->is_unsaved()) {
705 current->apply_code();
706 }
707 }
708
709 Control *c = tab_container->get_tab_control(p_idx);
710 if (!c) {
711 return;
712 }
713
714 if (history_pos >= 0 && history_pos < history.size() && history[history_pos].control == tab_container->get_current_tab_control()) {
715 Node *n = tab_container->get_current_tab_control();
716
717 if (Object::cast_to<ScriptEditorBase>(n)) {
718 history.write[history_pos].state = Object::cast_to<ScriptEditorBase>(n)->get_navigation_state();
719 }
720 if (Object::cast_to<EditorHelp>(n)) {
721 history.write[history_pos].state = Object::cast_to<EditorHelp>(n)->get_scroll();
722 }
723 }
724
725 history.resize(history_pos + 1);
726 ScriptHistory sh;
727 sh.control = c;
728 sh.state = Variant();
729
730 if (!lock_history && (history.is_empty() || history[history.size() - 1].control != sh.control)) {
731 history.push_back(sh);
732 history_pos++;
733 }
734
735 tab_container->set_current_tab(p_idx);
736
737 c = tab_container->get_current_tab_control();
738
739 ScriptEditorBase *seb = Object::cast_to<ScriptEditorBase>(c);
740 if (seb) {
741 if (is_visible_in_tree()) {
742 seb->ensure_focus();
743 }
744
745 Ref<Script> scr = seb->get_edited_resource();
746 if (scr.is_valid()) {
747 notify_script_changed(scr);
748 }
749
750 seb->validate();
751 }
752
753 EditorHelp *eh = Object::cast_to<EditorHelp>(c);
754 if (eh) {
755 script_name_label->set_text(eh->get_class());
756
757 if (is_visible_in_tree()) {
758 eh->set_focused();
759 }
760 }
761
762 c->set_meta("__editor_pass", ++edit_pass);
763 _update_history_arrows();
764 _update_script_colors();
765 _update_members_overview();
766 _update_help_overview();
767 _update_selected_editor_menu();
768 _update_online_doc();
769 _update_members_overview_visibility();
770 _update_help_overview_visibility();
771 }
772
773 void ScriptEditor::_add_recent_script(const String &p_path) {
774 if (p_path.is_empty()) {
775 return;
776 }
777
778 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scripts", Array());
779 if (rc.has(p_path)) {
780 rc.erase(p_path);
781 }
782 rc.push_front(p_path);
783 if (rc.size() > 10) {
784 rc.resize(10);
785 }
786
787 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scripts", rc);
788 _update_recent_scripts();
789 }
790
791 void ScriptEditor::_update_recent_scripts() {
792 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scripts", Array());
793 recent_scripts->clear();
794
795 String path;
796 for (int i = 0; i < rc.size(); i++) {
797 path = rc[i];
798 recent_scripts->add_item(path.replace("res://", ""));
799 }
800
801 recent_scripts->add_separator();
802 recent_scripts->add_shortcut(ED_GET_SHORTCUT("script_editor/clear_recent"));
803 recent_scripts->set_item_auto_translate_mode(-1, AUTO_TRANSLATE_MODE_ALWAYS);
804 recent_scripts->set_item_disabled(-1, rc.is_empty());
805
806 recent_scripts->reset_size();
807 }
808
809 void ScriptEditor::_open_recent_script(int p_idx) {
810 // clear button
811 if (p_idx == recent_scripts->get_item_count() - 1) {
812 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scripts", Array());
813 callable_mp(this, &ScriptEditor::_update_recent_scripts).call_deferred();
814 return;
815 }
816
817 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scripts", Array());
818 ERR_FAIL_INDEX(p_idx, rc.size());
819
820 String path = rc[p_idx];
821 // if its not on disk its a help file or deleted
822 if (FileAccess::exists(path)) {
823 List<String> extensions;
824 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
825 ResourceLoader::get_recognized_extensions_for_type("JSON", &extensions);
826
827 if (extensions.find(path.get_extension())) {
828 Ref<Resource> scr = ResourceLoader::load(path);
829 if (scr.is_valid()) {
830 edit(scr, true);
831 return;
832 }
833 }
834
835 Error err;
836 Ref<TextFile> text_file = _load_text_file(path, &err);
837 if (text_file.is_valid()) {
838 edit(text_file, true);
839 return;
840 }
841 // if it's a path then it's most likely a deleted file not help
842 } else if (path.contains("::")) {
843 // built-in script
844 String res_path = path.get_slice("::", 0);
845 EditorNode::get_singleton()->load_scene_or_resource(res_path, false, false);
846
847 Ref<Script> scr = ResourceLoader::load(path);
848 if (scr.is_valid()) {
849 edit(scr, true);
850 return;
851 }
852 } else if (!path.is_resource_file()) {
853 _help_class_open(path);
854 return;
855 }
856
857 rc.remove_at(p_idx);
858 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scripts", rc);
859 _update_recent_scripts();
860 _show_error_dialog(path);
861 }
862
863 void ScriptEditor::_show_error_dialog(const String &p_path) {
864 error_dialog->set_text(vformat(TTR("Can't open '%s'. The file could have been moved or deleted."), p_path));
865 error_dialog->popup_centered();
866 }
867
868 void ScriptEditor::_close_tab(int p_idx, bool p_save, bool p_history_back) {
869 int selected = p_idx;
870 if (selected < 0 || selected >= tab_container->get_tab_count()) {
871 return;
872 }
873
874 Node *tselected = tab_container->get_tab_control(selected);
875
876 ScriptEditorBase *current = Object::cast_to<ScriptEditorBase>(tselected);
877 if (current) {
878 Ref<Resource> file = current->get_edited_resource();
879 if (p_save && file.is_valid()) {
880 // Do not try to save internal scripts, but prompt to save in-memory
881 // scripts which are not saved to disk yet (have empty path).
882 if (!file->is_built_in()) {
883 save_current_script();
884 }
885 }
886 if (file.is_valid()) {
887 if (!file->get_path().is_empty()) {
888 // Only saved scripts can be restored.
889 previous_scripts.push_back(file->get_path());
890 }
891
892 Ref<Script> scr = file;
893 if (scr.is_valid()) {
894 notify_script_close(scr);
895 }
896 }
897 }
898
899 // roll back to previous tab
900 if (p_history_back) {
901 _history_back();
902 }
903
904 //remove from history
905 history.resize(history_pos + 1);
906
907 for (int i = 0; i < history.size(); i++) {
908 if (history[i].control == tselected) {
909 history.remove_at(i);
910 i--;
911 history_pos--;
912 }
913 }
914
915 if (history_pos >= history.size()) {
916 history_pos = history.size() - 1;
917 }
918
919 int idx = tab_container->get_current_tab();
920 if (current) {
921 current->clear_edit_menu();
922 _save_editor_state(current);
923 }
924 memdelete(tselected);
925
926 if (script_close_queue.is_empty()) {
927 if (idx >= tab_container->get_tab_count()) {
928 idx = tab_container->get_tab_count() - 1;
929 }
930 if (idx >= 0) {
931 if (history_pos >= 0) {
932 idx = tab_container->get_tab_idx_from_control(history[history_pos].control);
933 }
934 _go_to_tab(idx);
935 } else {
936 _update_selected_editor_menu();
937 _update_online_doc();
938 script_name_label->set_text(String());
939 }
940
941 _update_history_arrows();
942 _update_script_names();
943 _save_layout();
944 _update_find_replace_bar();
945 }
946 }
947
948 void ScriptEditor::_close_current_tab(bool p_save, bool p_history_back) {
949 _close_tab(tab_container->get_current_tab(), p_save, p_history_back);
950 }
951
952 void ScriptEditor::_close_discard_current_tab(const String &p_str) {
953 Ref<Script> scr = _get_current_script();
954 if (scr.is_valid()) {
955 scr->reload_from_file();
956 }
957 _close_tab(tab_container->get_current_tab(), false);
958 erase_tab_confirm->hide();
959 }
960
961 void ScriptEditor::_close_docs_tab() {
962 int child_count = tab_container->get_tab_count();
963 for (int i = child_count - 1; i >= 0; i--) {
964 EditorHelp *se = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
965
966 if (se) {
967 _close_tab(i, true, false);
968 }
969 }
970 }
971
972 void ScriptEditor::_copy_script_path() {
973 ScriptEditorBase *se = _get_current_editor();
974 if (se) {
975 Ref<Resource> scr = se->get_edited_resource();
976 DisplayServer::get_singleton()->clipboard_set(scr->get_path());
977 }
978 }
979
980 void ScriptEditor::_copy_script_uid() {
981 ScriptEditorBase *se = _get_current_editor();
982 if (se) {
983 Ref<Resource> scr = se->get_edited_resource();
984 ResourceUID::ID uid = ResourceLoader::get_resource_uid(scr->get_path());
985 DisplayServer::get_singleton()->clipboard_set(ResourceUID::get_singleton()->id_to_text(uid));
986 }
987 }
988
989 void ScriptEditor::_close_other_tabs() {
990 int current_idx = tab_container->get_current_tab();
991 for (int i = tab_container->get_tab_count() - 1; i >= 0; i--) {
992 if (i != current_idx) {
993 script_close_queue.push_back(i);
994 }
995 }
996 _queue_close_tabs();
997 }
998
999 void ScriptEditor::_close_tabs_below() {
1000 int current_idx = tab_container->get_current_tab();
1001 for (int i = tab_container->get_tab_count() - 1; i > current_idx; i--) {
1002 script_close_queue.push_back(i);
1003 }
1004 _go_to_tab(current_idx);
1005 _queue_close_tabs();
1006 }
1007
1008 void ScriptEditor::_close_all_tabs() {
1009 for (int i = tab_container->get_tab_count() - 1; i >= 0; i--) {
1010 script_close_queue.push_back(i);
1011 }
1012 _queue_close_tabs();
1013 }
1014
1015 void ScriptEditor::_queue_close_tabs() {
1016 while (!script_close_queue.is_empty()) {
1017 int idx = script_close_queue.front()->get();
1018 script_close_queue.pop_front();
1019
1020 tab_container->set_current_tab(idx);
1021 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(idx));
1022 if (se) {
1023 // Maybe there are unsaved changes.
1024 if (se->is_unsaved()) {
1025 _ask_close_current_unsaved_tab(se);
1026 erase_tab_confirm->connect(SceneStringName(visibility_changed), callable_mp(this, &ScriptEditor::_queue_close_tabs), CONNECT_ONE_SHOT);
1027 break;
1028 }
1029 }
1030
1031 _close_current_tab(false, false);
1032 }
1033 _update_find_replace_bar();
1034 }
1035
1036 void ScriptEditor::_ask_close_current_unsaved_tab(ScriptEditorBase *current) {
1037 erase_tab_confirm->set_text(TTR("Close and save changes?") + "\n\"" + current->get_name() + "\"");
1038 erase_tab_confirm->popup_centered();
1039 }
1040
1041 void ScriptEditor::_resave_scripts(const String &p_str) {
1042 apply_scripts();
1043
1044 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1045 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1046 if (!se) {
1047 continue;
1048 }
1049
1050 Ref<Resource> scr = se->get_edited_resource();
1051
1052 if (scr->is_built_in()) {
1053 continue; // Internal script, who cares.
1054 }
1055
1056 if (trim_trailing_whitespace_on_save) {
1057 se->trim_trailing_whitespace();
1058 }
1059
1060 if (trim_final_newlines_on_save) {
1061 se->trim_final_newlines();
1062 }
1063
1064 if (convert_indent_on_save) {
1065 se->convert_indent();
1066 }
1067
1068 Ref<TextFile> text_file = scr;
1069 if (text_file.is_valid()) {
1070 se->apply_code();
1071 _save_text_file(text_file, text_file->get_path());
1072 break;
1073 } else {
1074 EditorNode::get_singleton()->save_resource(scr);
1075 }
1076 se->tag_saved_version();
1077 }
1078
1079 disk_changed->hide();
1080 }
1081
1082 void ScriptEditor::_res_saved_callback(const Ref<Resource> &p_res) {
1083 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1084 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1085 if (!se) {
1086 continue;
1087 }
1088
1089 Ref<Resource> scr = se->get_edited_resource();
1090
1091 if (scr == p_res) {
1092 se->tag_saved_version();
1093 }
1094 }
1095
1096 if (p_res.is_valid()) {
1097 // In case the Resource has built-in scripts.
1098 _mark_built_in_scripts_as_saved(p_res->get_path());
1099 }
1100
1101 _update_script_names();
1102 Ref<Script> scr = p_res;
1103 if (scr.is_valid()) {
1104 trigger_live_script_reload(scr->get_path());
1105 }
1106 }
1107
1108 void ScriptEditor::_scene_saved_callback(const String &p_path) {
1109 // If scene was saved, mark all built-in scripts from that scene as saved.
1110 _mark_built_in_scripts_as_saved(p_path);
1111 }
1112
1113 void ScriptEditor::_mark_built_in_scripts_as_saved(const String &p_parent_path) {
1114 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1115 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1116 if (!se) {
1117 continue;
1118 }
1119
1120 Ref<Resource> edited_res = se->get_edited_resource();
1121 if (!edited_res->is_built_in()) {
1122 continue; // External script, who cares.
1123 }
1124
1125 if (edited_res->get_path().get_slice("::", 0) != p_parent_path) {
1126 continue; // Wrong scene.
1127 }
1128 se->tag_saved_version();
1129
1130 Ref<Script> scr = edited_res;
1131 if (scr.is_valid()) {
1132 trigger_live_script_reload(scr->get_path());
1133 clear_docs_from_script(scr);
1134 scr->reload(true);
1135 update_docs_from_script(scr);
1136 }
1137 }
1138 }
1139
1140 void ScriptEditor::trigger_live_script_reload(const String &p_script_path) {
1141 if (!script_paths_to_reload.has(p_script_path)) {
1142 Ref<Script> reloaded_script = ResourceCache::get_ref(p_script_path);
1143 if (reloaded_script.is_null()) {
1144 reloaded_script = ResourceLoader::load(p_script_path);
1145 }
1146 if (reloaded_script.is_valid()) {
1147 if (!reloaded_script->get_language()->validate(reloaded_script->get_source_code(), p_script_path)) {
1148 // Script has errors, don't live reload.
1149 return;
1150 }
1151 }
1152
1153 script_paths_to_reload.append(p_script_path);
1154 }
1155 if (!pending_auto_reload && auto_reload_running_scripts) {
1156 callable_mp(this, &ScriptEditor::_live_auto_reload_running_scripts).call_deferred();
1157 pending_auto_reload = true;
1158 }
1159 }
1160
1161 void ScriptEditor::_live_auto_reload_running_scripts() {
1162 pending_auto_reload = false;
1163 EditorDebuggerNode::get_singleton()->reload_scripts(script_paths_to_reload);
1164 script_paths_to_reload.clear();
1165 }
1166
1167 bool ScriptEditor::_test_script_times_on_disk(Ref<Resource> p_for_script) {
1168 disk_changed_list->clear();
1169 TreeItem *r = disk_changed_list->create_item();
1170
1171 bool need_ask = false;
1172 bool need_reload = false;
1173 bool use_autoreload = EDITOR_GET("text_editor/behavior/files/auto_reload_scripts_on_external_change");
1174
1175 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1176 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1177 if (se) {
1178 Ref<Resource> edited_res = se->get_edited_resource();
1179 if (p_for_script.is_valid() && edited_res.is_valid() && p_for_script != edited_res) {
1180 continue;
1181 }
1182
1183 if (edited_res->is_built_in()) {
1184 continue; // Internal script, who cares.
1185 }
1186
1187 uint64_t last_date = se->edited_file_data.last_modified_time;
1188 uint64_t date = FileAccess::get_modified_time(se->edited_file_data.path);
1189
1190 if (last_date != date) {
1191 TreeItem *ti = disk_changed_list->create_item(r);
1192 ti->set_text(0, se->edited_file_data.path.get_file());
1193
1194 if (!use_autoreload || se->is_unsaved()) {
1195 need_ask = true;
1196 }
1197 need_reload = true;
1198 }
1199 }
1200 }
1201
1202 if (need_reload) {
1203 if (!need_ask) {
1204 script_editor->reload_scripts();
1205 need_reload = false;
1206 } else {
1207 callable_mp((Window *)disk_changed, &Window::popup_centered_ratio).call_deferred(0.3);
1208 }
1209 }
1210
1211 return need_reload;
1212 }
1213
1214 void _import_text_editor_theme(const String &p_file) {
1215 if (p_file.get_extension() != "tet") {
1216 EditorToaster::get_singleton()->popup_str(TTR("Importing theme failed. File is not a text editor theme file (.tet)."), EditorToaster::SEVERITY_ERROR);
1217 return;
1218 }
1219 const String theme_name = p_file.get_file().get_basename();
1220 if (EditorSettings::is_default_text_editor_theme(theme_name.to_lower())) {
1221 EditorToaster::get_singleton()->popup_str(TTR("Importing theme failed. File name cannot be 'Default', 'Custom', or 'Godot 2'."), EditorToaster::SEVERITY_ERROR);
1222 return;
1223 }
1224
1225 const String theme_dir = EditorPaths::get_singleton()->get_text_editor_themes_dir();
1226 Ref<DirAccess> d = DirAccess::open(theme_dir);
1227 Error err = FAILED;
1228 if (d.is_valid()) {
1229 err = d->copy(p_file, theme_dir.path_join(p_file.get_file()));
1230 }
1231
1232 if (err != OK) {
1233 EditorToaster::get_singleton()->popup_str(TTR("Importing theme failed. Failed to copy theme file."), EditorToaster::SEVERITY_ERROR);
1234 return;
1235 }
1236
1237 // Reload themes and switch to new theme.
1238 EditorSettings::get_singleton()->update_text_editor_themes_list();
1239 EditorSettings::get_singleton()->set_manually("text_editor/theme/color_theme", theme_name, true);
1240 EditorSettings::get_singleton()->notify_changes();
1241 }
1242
1243 void _save_text_editor_theme_as(const String &p_file) {
1244 String file = p_file;
1245 if (p_file.get_extension() != "tet") {
1246 file += ".tet";
1247 }
1248
1249 const String theme_name = file.get_file().get_basename();
1250 if (EditorSettings::is_default_text_editor_theme(theme_name.to_lower())) {
1251 EditorToaster::get_singleton()->popup_str(TTR("Saving theme failed. File name cannot be 'Default', 'Custom', or 'Godot 2'."), EditorToaster::SEVERITY_ERROR);
1252 return;
1253 }
1254
1255 const String theme_section = "color_theme";
1256 const Ref<ConfigFile> cf = memnew(ConfigFile);
1257
1258 // Use the keys from the Godot 2 theme to know which settings to save.
1259 HashMap<StringName, Color> text_colors = EditorSettings::get_godot2_text_editor_theme();
1260 text_colors.sort();
1261 for (const KeyValue<StringName, Color> &text_color : text_colors) {
1262 const Color val = EditorSettings::get_singleton()->get_setting(text_color.key);
1263 const String &key = text_color.key.operator String().replace("text_editor/theme/highlighting/", "");
1264 cf->set_value(theme_section, key, val.to_html());
1265 }
1266
1267 const Error err = cf->save(file);
1268 if (err != OK) {
1269 EditorToaster::get_singleton()->popup_str(TTR("Saving theme failed."), EditorToaster::SEVERITY_ERROR);
1270 return;
1271 }
1272
1273 // Reload themes and switch to saved theme.
1274 EditorSettings::get_singleton()->update_text_editor_themes_list();
1275 if (p_file.get_base_dir() == EditorPaths::get_singleton()->get_text_editor_themes_dir()) {
1276 // Don't need to emit signal or notify changes as the colors are already set.
1277 EditorSettings::get_singleton()->set_manually("text_editor/theme/color_theme", theme_name, false);
1278 }
1279 }
1280
1281 bool ScriptEditor::_script_exists(const String &p_path) const {
1282 if (p_path.is_empty()) {
1283 return false;
1284 } else if (p_path.is_resource_file()) {
1285 return FileAccess::exists(p_path);
1286 } else {
1287 return FileAccess::exists(p_path.get_slice("::", 0));
1288 }
1289 }
1290
1291 void ScriptEditor::_file_dialog_action(const String &p_file) {
1292 switch (file_dialog_option) {
1293 case FILE_MENU_NEW_TEXTFILE: {
1294 Error err;
1295 {
1296 Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err);
1297 if (err) {
1298 EditorNode::get_singleton()->show_warning(TTR("Error writing TextFile:") + "\n" + p_file, TTR("Error!"));
1299 break;
1300 }
1301 }
1302
1303 if (EditorFileSystem::get_singleton()) {
1304 if (textfile_extensions.has(p_file.get_extension())) {
1305 EditorFileSystem::get_singleton()->update_file(p_file);
1306 }
1307 }
1308 [[fallthrough]];
1309 }
1310 case FILE_MENU_OPEN: {
1311 if (!is_visible_in_tree()) {
1312 // When created from outside the editor.
1313 EditorNode::get_singleton()->get_editor_main_screen()->select(EditorMainScreen::EDITOR_SCRIPT);
1314 }
1315 open_file(p_file);
1316 file_dialog_option = -1;
1317 } break;
1318 case FILE_MENU_SAVE_AS: {
1319 ScriptEditorBase *current = _get_current_editor();
1320 if (current) {
1321 Ref<Resource> resource = current->get_edited_resource();
1322 String path = ProjectSettings::get_singleton()->localize_path(p_file);
1323 Error err = _save_text_file(resource, path);
1324
1325 if (err != OK) {
1326 EditorNode::get_singleton()->show_accept(TTR("Error saving file!"), TTR("OK"));
1327 return;
1328 }
1329
1330 resource->set_path(path);
1331 _update_script_names();
1332 }
1333 } break;
1334 case THEME_SAVE_AS: {
1335 _save_text_editor_theme_as(p_file);
1336 } break;
1337 case THEME_IMPORT: {
1338 _import_text_editor_theme(p_file);
1339 } break;
1340 }
1341 file_dialog_option = -1;
1342 }
1343
1344 Ref<Script> ScriptEditor::_get_current_script() {
1345 ScriptEditorBase *current = _get_current_editor();
1346
1347 if (current) {
1348 Ref<Script> scr = current->get_edited_resource();
1349 return scr.is_valid() ? scr : nullptr;
1350 } else {
1351 return nullptr;
1352 }
1353 }
1354
1355 TypedArray<Script> ScriptEditor::_get_open_scripts() const {
1356 TypedArray<Script> ret;
1357 Vector<Ref<Script>> scripts = get_open_scripts();
1358 int scripts_amount = scripts.size();
1359 for (int idx_script = 0; idx_script < scripts_amount; idx_script++) {
1360 ret.push_back(scripts[idx_script]);
1361 }
1362 return ret;
1363 }
1364
1365 bool ScriptEditor::toggle_files_panel() {
1366 list_split->set_visible(!list_split->is_visible());
1367 EditorSettings::get_singleton()->set_project_metadata("files_panel", "show_files_panel", list_split->is_visible());
1368 return list_split->is_visible();
1369 }
1370
1371 bool ScriptEditor::is_files_panel_toggled() {
1372 return list_split->is_visible();
1373 }
1374
1375 void ScriptEditor::_menu_option(int p_option) {
1376 ScriptEditorBase *current = _get_current_editor();
1377 switch (p_option) {
1378 case FILE_MENU_NEW: {
1379 script_create_dialog->config("Node", "new_script", false, false);
1380 script_create_dialog->popup_centered();
1381 } break;
1382 case FILE_MENU_NEW_TEXTFILE: {
1383 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
1384 file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1385 file_dialog_option = FILE_MENU_NEW_TEXTFILE;
1386
1387 file_dialog->clear_filters();
1388 for (const String &E : textfile_extensions) {
1389 file_dialog->add_filter("*." + E, E.to_upper());
1390 }
1391 file_dialog->set_title(TTRC("New Text File..."));
1392 file_dialog->popup_file_dialog();
1393 } break;
1394 case FILE_MENU_OPEN: {
1395 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
1396 file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1397 file_dialog_option = FILE_MENU_OPEN;
1398
1399 List<String> extensions;
1400 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
1401 file_dialog->clear_filters();
1402 for (const String &extension : extensions) {
1403 file_dialog->add_filter("*." + extension, extension.to_upper());
1404 }
1405
1406 for (const String &E : textfile_extensions) {
1407 file_dialog->add_filter("*." + E, E.to_upper());
1408 }
1409
1410 file_dialog->set_title(TTRC("Open File"));
1411 file_dialog->popup_file_dialog();
1412 return;
1413 } break;
1414 case FILE_MENU_REOPEN_CLOSED: {
1415 if (previous_scripts.is_empty()) {
1416 return;
1417 }
1418
1419 String path = previous_scripts.back()->get();
1420 previous_scripts.pop_back();
1421
1422 List<String> extensions;
1423 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
1424 ResourceLoader::get_recognized_extensions_for_type("JSON", &extensions);
1425 bool built_in = !path.is_resource_file();
1426
1427 if (extensions.find(path.get_extension()) || built_in) {
1428 if (built_in) {
1429 String res_path = path.get_slice("::", 0);
1430 EditorNode::get_singleton()->load_scene_or_resource(res_path, false, false);
1431 }
1432
1433 Ref<Resource> scr = ResourceLoader::load(path);
1434 if (scr.is_null()) {
1435 EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + path, TTR("Error!"));
1436 file_dialog_option = -1;
1437 return;
1438 }
1439
1440 edit(scr);
1441 file_dialog_option = -1;
1442 } else {
1443 Error error;
1444 Ref<TextFile> text_file = _load_text_file(path, &error);
1445 if (error != OK) {
1446 EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + path, TTR("Error!"));
1447 }
1448
1449 if (text_file.is_valid()) {
1450 edit(text_file);
1451 file_dialog_option = -1;
1452 }
1453 }
1454 } break;
1455 case FILE_MENU_SAVE_ALL: {
1456 if (_test_script_times_on_disk()) {
1457 return;
1458 }
1459
1460 save_all_scripts();
1461 } break;
1462 case SEARCH_IN_FILES: {
1463 open_find_in_files_dialog("");
1464 } break;
1465 case REPLACE_IN_FILES: {
1466 _on_replace_in_files_requested("");
1467 } break;
1468 case SEARCH_HELP: {
1469 help_search_dialog->popup_dialog();
1470 } break;
1471 case SEARCH_WEBSITE: {
1472 Control *tab = tab_container->get_current_tab_control();
1473
1474 EditorHelp *eh = Object::cast_to<EditorHelp>(tab);
1475 bool native_class_doc = false;
1476 if (eh) {
1477 const HashMap<String, DocData::ClassDoc>::ConstIterator E = EditorHelp::get_doc_data()->class_list.find(eh->get_class());
1478 native_class_doc = E && !E->value.is_script_doc;
1479 }
1480 if (native_class_doc) {
1481 String name = eh->get_class().to_lower();
1482 String doc_url = vformat(GODOT_VERSION_DOCS_URL "/classes/class_%s.html", name);
1483 OS::get_singleton()->shell_open(doc_url);
1484 } else {
1485 OS::get_singleton()->shell_open(GODOT_VERSION_DOCS_URL "/");
1486 }
1487 } break;
1488 case FILE_MENU_HISTORY_NEXT: {
1489 _history_forward();
1490 } break;
1491 case FILE_MENU_HISTORY_PREV: {
1492 _history_back();
1493 } break;
1494 case FILE_MENU_SORT: {
1495 _sort_list_on_update = true;
1496 _update_script_names();
1497 } break;
1498 case FILE_MENU_TOGGLE_FILES_PANEL: {
1499 toggle_files_panel();
1500 if (current) {
1501 current->update_toggle_files_button();
1502 } else {
1503 Control *tab = tab_container->get_current_tab_control();
1504 EditorHelp *editor_help = Object::cast_to<EditorHelp>(tab);
1505 if (editor_help) {
1506 editor_help->update_toggle_files_button();
1507 }
1508 }
1509 }
1510 }
1511
1512 if (p_option >= EditorContextMenuPlugin::BASE_ID) {
1513 Ref<Resource> resource;
1514 if (current) {
1515 resource = current->get_edited_resource();
1516 }
1517 EditorContextMenuPluginManager::get_singleton()->activate_custom_option(EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR, p_option, resource);
1518 return;
1519 }
1520
1521 if (current) {
1522 switch (p_option) {
1523 case FILE_MENU_SAVE: {
1524 save_current_script();
1525 } break;
1526 case FILE_MENU_SAVE_AS: {
1527 if (trim_trailing_whitespace_on_save) {
1528 current->trim_trailing_whitespace();
1529 }
1530
1531 if (trim_final_newlines_on_save) {
1532 current->trim_final_newlines();
1533 }
1534
1535 if (convert_indent_on_save) {
1536 current->convert_indent();
1537 }
1538
1539 Ref<Resource> resource = current->get_edited_resource();
1540 Ref<TextFile> text_file = resource;
1541 Ref<Script> scr = resource;
1542
1543 if (text_file.is_valid()) {
1544 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
1545 file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1546 file_dialog_option = FILE_MENU_SAVE_AS;
1547
1548 List<String> extensions;
1549 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
1550 file_dialog->clear_filters();
1551 file_dialog->set_current_dir(text_file->get_path().get_base_dir());
1552 file_dialog->set_current_file(text_file->get_path().get_file());
1553 file_dialog->set_title(TTRC("Save File As..."));
1554 file_dialog->popup_file_dialog();
1555 break;
1556 }
1557
1558 if (scr.is_valid()) {
1559 clear_docs_from_script(scr);
1560 }
1561
1562 EditorNode::get_singleton()->push_item(resource.ptr());
1563 EditorNode::get_singleton()->save_resource_as(resource);
1564
1565 if (scr.is_valid()) {
1566 update_docs_from_script(scr);
1567 }
1568 } break;
1569
1570 case FILE_MENU_SOFT_RELOAD_TOOL: {
1571 Ref<Script> scr = current->get_edited_resource();
1572 if (scr.is_null()) {
1573 EditorNode::get_singleton()->show_warning(TTR("Can't obtain the script for reloading."));
1574 break;
1575 }
1576 if (!scr->is_tool()) {
1577 EditorNode::get_singleton()->show_warning(TTR("Reload only takes effect on tool scripts."));
1578 return;
1579 }
1580 scr->reload(true);
1581
1582 } break;
1583
1584 case FILE_MENU_RUN: {
1585 Ref<Script> scr = current->get_edited_resource();
1586 if (scr.is_null()) {
1587 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the edited file because it's not a script."), EditorToaster::SEVERITY_WARNING);
1588 break;
1589 }
1590
1591 current->apply_code();
1592
1593 EditorNode::get_singleton()->run_editor_script(scr);
1594 } break;
1595
1596 case FILE_MENU_CLOSE: {
1597 if (current->is_unsaved()) {
1598 _ask_close_current_unsaved_tab(current);
1599 } else {
1600 _close_current_tab(false);
1601 }
1602 } break;
1603 case FILE_MENU_COPY_PATH: {
1604 _copy_script_path();
1605 } break;
1606 case FILE_MENU_COPY_UID: {
1607 _copy_script_uid();
1608 } break;
1609 case FILE_MENU_SHOW_IN_FILE_SYSTEM: {
1610 const Ref<Resource> scr = current->get_edited_resource();
1611 String path = scr->get_path();
1612 if (!path.is_empty()) {
1613 if (scr->is_built_in()) {
1614 path = path.get_slice("::", 0); // Show the scene instead.
1615 }
1616
1617 FileSystemDock::get_singleton()->navigate_to_path(path);
1618 }
1619 } break;
1620 case FILE_MENU_CLOSE_DOCS: {
1621 _close_docs_tab();
1622 } break;
1623 case FILE_MENU_CLOSE_OTHER_TABS: {
1624 _close_other_tabs();
1625 } break;
1626 case FILE_MENU_CLOSE_TABS_BELOW: {
1627 _close_tabs_below();
1628 } break;
1629 case FILE_MENU_CLOSE_ALL: {
1630 _close_all_tabs();
1631 } break;
1632 case FILE_MENU_MOVE_UP: {
1633 if (tab_container->get_current_tab() > 0) {
1634 tab_container->move_child(current, tab_container->get_current_tab() - 1);
1635 tab_container->set_current_tab(tab_container->get_current_tab());
1636 _update_script_names();
1637 }
1638 } break;
1639 case FILE_MENU_MOVE_DOWN: {
1640 if (tab_container->get_current_tab() < tab_container->get_tab_count() - 1) {
1641 tab_container->move_child(current, tab_container->get_current_tab() + 1);
1642 tab_container->set_current_tab(tab_container->get_current_tab());
1643 _update_script_names();
1644 }
1645 } break;
1646 }
1647 } else {
1648 EditorHelp *help = Object::cast_to<EditorHelp>(tab_container->get_current_tab_control());
1649 if (help) {
1650 switch (p_option) {
1651 case HELP_SEARCH_FIND: {
1652 help->popup_search();
1653 } break;
1654 case HELP_SEARCH_FIND_NEXT: {
1655 help->search_again();
1656 } break;
1657 case HELP_SEARCH_FIND_PREVIOUS: {
1658 help->search_again(true);
1659 } break;
1660 case FILE_MENU_CLOSE: {
1661 _close_current_tab();
1662 } break;
1663 case FILE_MENU_CLOSE_DOCS: {
1664 _close_docs_tab();
1665 } break;
1666 case FILE_MENU_CLOSE_OTHER_TABS: {
1667 _close_other_tabs();
1668 } break;
1669 case FILE_MENU_CLOSE_TABS_BELOW: {
1670 _close_tabs_below();
1671 } break;
1672 case FILE_MENU_CLOSE_ALL: {
1673 _close_all_tabs();
1674 } break;
1675 case FILE_MENU_MOVE_UP: {
1676 if (tab_container->get_current_tab() > 0) {
1677 tab_container->move_child(help, tab_container->get_current_tab() - 1);
1678 tab_container->set_current_tab(tab_container->get_current_tab());
1679 _update_script_names();
1680 }
1681 } break;
1682 case FILE_MENU_MOVE_DOWN: {
1683 if (tab_container->get_current_tab() < tab_container->get_tab_count() - 1) {
1684 tab_container->move_child(help, tab_container->get_current_tab() + 1);
1685 tab_container->set_current_tab(tab_container->get_current_tab());
1686 _update_script_names();
1687 }
1688 } break;
1689 }
1690 }
1691 }
1692 }
1693
1694 void ScriptEditor::_theme_option(int p_option) {
1695 switch (p_option) {
1696 case THEME_IMPORT: {
1697 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
1698 file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1699 file_dialog_option = THEME_IMPORT;
1700 file_dialog->clear_filters();
1701 file_dialog->add_filter("*.tet");
1702 file_dialog->set_title(TTRC("Import Theme"));
1703 file_dialog->popup_file_dialog();
1704 } break;
1705 case THEME_RELOAD: {
1706 EditorSettings::get_singleton()->mark_setting_changed("text_editor/theme/color_theme");
1707 EditorSettings::get_singleton()->notify_changes();
1708 } break;
1709 case THEME_SAVE_AS: {
1710 ScriptEditor::_show_save_theme_as_dialog();
1711 } break;
1712 }
1713 }
1714
1715 void ScriptEditor::_show_save_theme_as_dialog() {
1716 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
1717 file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1718 file_dialog_option = THEME_SAVE_AS;
1719 file_dialog->clear_filters();
1720 file_dialog->add_filter("*.tet");
1721 file_dialog->set_current_path(EditorPaths::get_singleton()->get_text_editor_themes_dir().path_join(EDITOR_GET("text_editor/theme/color_theme")) + " New");
1722 file_dialog->set_title(TTRC("Save Theme As..."));
1723 file_dialog->popup_file_dialog();
1724 }
1725
1726 bool ScriptEditor::_has_docs_tab() const {
1727 const int child_count = tab_container->get_tab_count();
1728 for (int i = 0; i < child_count; i++) {
1729 if (Object::cast_to<EditorHelp>(tab_container->get_tab_control(i))) {
1730 return true;
1731 }
1732 }
1733 return false;
1734 }
1735
1736 bool ScriptEditor::_has_script_tab() const {
1737 const int child_count = tab_container->get_tab_count();
1738 for (int i = 0; i < child_count; i++) {
1739 if (Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i))) {
1740 return true;
1741 }
1742 }
1743 return false;
1744 }
1745
1746 void ScriptEditor::_prepare_file_menu() {
1747 PopupMenu *menu = file_menu->get_popup();
1748 ScriptEditorBase *editor = _get_current_editor();
1749 const Ref<Resource> res = editor ? editor->get_edited_resource() : Ref<Resource>();
1750
1751 menu->set_item_disabled(menu->get_item_index(FILE_MENU_REOPEN_CLOSED), previous_scripts.is_empty());
1752
1753 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE), res.is_null());
1754 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE_AS), res.is_null());
1755 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE_ALL), !_has_script_tab());
1756
1757 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SOFT_RELOAD_TOOL), res.is_null());
1758 menu->set_item_disabled(menu->get_item_index(FILE_MENU_COPY_PATH), res.is_null() || res->get_path().is_empty());
1759 menu->set_item_disabled(menu->get_item_index(FILE_MENU_COPY_UID), res.is_null() || ResourceLoader::get_resource_uid(res->get_path()) == ResourceUID::INVALID_ID);
1760 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SHOW_IN_FILE_SYSTEM), res.is_null());
1761
1762 menu->set_item_disabled(menu->get_item_index(FILE_MENU_HISTORY_PREV), history_pos <= 0);
1763 menu->set_item_disabled(menu->get_item_index(FILE_MENU_HISTORY_NEXT), history_pos >= history.size() - 1);
1764
1765 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE), tab_container->get_tab_count() < 1);
1766 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_ALL), tab_container->get_tab_count() < 1);
1767 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_OTHER_TABS), tab_container->get_tab_count() <= 1);
1768 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_TABS_BELOW), tab_container->get_current_tab() >= tab_container->get_tab_count() - 1);
1769 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_DOCS), !_has_docs_tab());
1770
1771 menu->set_item_disabled(menu->get_item_index(FILE_MENU_RUN), res.is_null());
1772 }
1773
1774 void ScriptEditor::_file_menu_closed() {
1775 PopupMenu *menu = file_menu->get_popup();
1776
1777 menu->set_item_disabled(menu->get_item_index(FILE_MENU_REOPEN_CLOSED), false);
1778
1779 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE), false);
1780 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE_AS), false);
1781 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SAVE_ALL), false);
1782
1783 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SOFT_RELOAD_TOOL), false);
1784 menu->set_item_disabled(menu->get_item_index(FILE_MENU_COPY_PATH), false);
1785 menu->set_item_disabled(menu->get_item_index(FILE_MENU_SHOW_IN_FILE_SYSTEM), false);
1786
1787 menu->set_item_disabled(menu->get_item_index(FILE_MENU_HISTORY_PREV), false);
1788 menu->set_item_disabled(menu->get_item_index(FILE_MENU_HISTORY_NEXT), false);
1789
1790 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE), false);
1791 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_ALL), false);
1792 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_OTHER_TABS), false);
1793 menu->set_item_disabled(menu->get_item_index(FILE_MENU_CLOSE_DOCS), false);
1794
1795 menu->set_item_disabled(menu->get_item_index(FILE_MENU_RUN), false);
1796 }
1797
1798 void ScriptEditor::_tab_changed(int p_which) {
1799 ensure_select_current();
1800 }
1801
1802 void ScriptEditor::_notification(int p_what) {
1803 switch (p_what) {
1804 case NOTIFICATION_ENTER_TREE: {
1805 EditorRunBar::get_singleton()->connect("stop_pressed", callable_mp(this, &ScriptEditor::_editor_stop));
1806 _apply_editor_settings();
1807 [[fallthrough]];
1808 }
1809
1810 case NOTIFICATION_TRANSLATION_CHANGED: {
1811 _update_online_doc();
1812 if (!make_floating->is_disabled()) {
1813 // Override default ScreenSelect tooltip if multi-window support is available.
1814 make_floating->set_tooltip_text(TTR("Make the script editor floating.") + "\n" + TTR("Right-click to open the screen selector."));
1815 }
1816 [[fallthrough]];
1817 }
1818 case NOTIFICATION_LAYOUT_DIRECTION_CHANGED:
1819 case NOTIFICATION_THEME_CHANGED: {
1820 tab_container->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("ScriptEditor"), EditorStringName(EditorStyles)));
1821
1822 help_search->set_button_icon(get_editor_theme_icon(SNAME("HelpSearch")));
1823 site_search->set_button_icon(get_editor_theme_icon(SNAME("ExternalLink")));
1824
1825 if (is_layout_rtl()) {
1826 script_forward->set_button_icon(get_editor_theme_icon(SNAME("Back")));
1827 script_back->set_button_icon(get_editor_theme_icon(SNAME("Forward")));
1828 } else {
1829 script_forward->set_button_icon(get_editor_theme_icon(SNAME("Forward")));
1830 script_back->set_button_icon(get_editor_theme_icon(SNAME("Back")));
1831 }
1832
1833 members_overview_alphabeta_sort_button->set_button_icon(get_editor_theme_icon(SNAME("Sort")));
1834
1835 filter_scripts->set_right_icon(get_editor_theme_icon(SNAME("Search")));
1836 filter_methods->set_right_icon(get_editor_theme_icon(SNAME("Search")));
1837
1838 recent_scripts->reset_size();
1839 script_list->set_fixed_icon_size(Vector2i(1, 1) * get_theme_constant("class_icon_size", EditorStringName(Editor)));
1840
1841 if (is_inside_tree()) {
1842 _update_script_names();
1843 }
1844 } break;
1845
1846 case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
1847 if (EditorThemeManager::is_generated_theme_outdated() ||
1848 EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor") ||
1849 EditorSettings::get_singleton()->check_changed_settings_in_group("text_editor") ||
1850 EditorSettings::get_singleton()->check_changed_settings_in_group("docks/filesystem")) {
1851 _apply_editor_settings();
1852 }
1853 } break;
1854
1855 case NOTIFICATION_READY: {
1856 // Can't set own styles in NOTIFICATION_THEME_CHANGED, so for now this will do.
1857 add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("ScriptEditorPanel"), EditorStringName(EditorStyles)));
1858
1859 get_tree()->connect("tree_changed", callable_mp(this, &ScriptEditor::_tree_changed));
1860 InspectorDock::get_singleton()->connect("request_help", callable_mp(this, &ScriptEditor::_help_class_open));
1861 EditorNode::get_singleton()->connect("request_help_search", callable_mp(this, &ScriptEditor::_help_search));
1862 EditorNode::get_singleton()->connect("scene_closed", callable_mp(this, &ScriptEditor::_close_builtin_scripts_from_scene));
1863 EditorNode::get_singleton()->connect("script_add_function_request", callable_mp(this, &ScriptEditor::_add_callback));
1864 EditorNode::get_singleton()->connect("resource_saved", callable_mp(this, &ScriptEditor::_res_saved_callback));
1865 EditorNode::get_singleton()->connect("scene_saved", callable_mp(this, &ScriptEditor::_scene_saved_callback));
1866 FileSystemDock::get_singleton()->connect("files_moved", callable_mp(this, &ScriptEditor::_files_moved));
1867 FileSystemDock::get_singleton()->connect("file_removed", callable_mp(this, &ScriptEditor::_file_removed));
1868 script_list->connect(SceneStringName(item_selected), callable_mp(this, &ScriptEditor::_script_selected));
1869
1870 members_overview->connect(SceneStringName(item_selected), callable_mp(this, &ScriptEditor::_members_overview_selected));
1871 help_overview->connect(SceneStringName(item_selected), callable_mp(this, &ScriptEditor::_help_overview_selected));
1872 script_split->connect("dragged", callable_mp(this, &ScriptEditor::_split_dragged));
1873 list_split->connect("dragged", callable_mp(this, &ScriptEditor::_split_dragged));
1874
1875 EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &ScriptEditor::_filesystem_changed));
1876 #ifdef ANDROID_ENABLED
1877 set_process(true);
1878 #endif
1879 } break;
1880
1881 #ifdef ANDROID_ENABLED
1882 case NOTIFICATION_VISIBILITY_CHANGED: {
1883 set_process(is_visible_in_tree());
1884 } break;
1885
1886 case NOTIFICATION_PROCESS: {
1887 const int kb_height = DisplayServer::get_singleton()->virtual_keyboard_get_height();
1888 if (kb_height == last_kb_height) {
1889 break;
1890 }
1891
1892 last_kb_height = kb_height;
1893 float spacer_height = 0.0f;
1894 const float status_bar_height = 28 * EDSCALE; // Magic number
1895 const bool kb_visible = kb_height > 0;
1896
1897 if (kb_visible) {
1898 if (ScriptEditorBase *editor = _get_current_editor()) {
1899 if (CodeTextEditor *code_editor = editor->get_code_editor()) {
1900 if (CodeEdit *text_editor = code_editor->get_text_editor()) {
1901 if (!text_editor->has_focus()) {
1902 break;
1903 }
1904 text_editor->adjust_viewport_to_caret();
1905 }
1906 }
1907 }
1908
1909 const float control_bottom = get_global_position().y + get_size().y;
1910 const float extra_bottom = get_viewport_rect().size.y - control_bottom;
1911 spacer_height = float(kb_height) - extra_bottom - status_bar_height;
1912
1913 if (spacer_height < 0.0f) {
1914 spacer_height = 0.0f;
1915 }
1916 }
1917
1918 virtual_keyboard_spacer->set_custom_minimum_size(Size2(0, spacer_height));
1919 EditorSceneTabs::get_singleton()->set_visible(!kb_height);
1920 menu_hb->set_visible(!kb_visible);
1921 } break;
1922 #endif
1923
1924 case NOTIFICATION_EXIT_TREE: {
1925 EditorRunBar::get_singleton()->disconnect("stop_pressed", callable_mp(this, &ScriptEditor::_editor_stop));
1926 } break;
1927
1928 case NOTIFICATION_APPLICATION_FOCUS_IN: {
1929 if (is_inside_tree()) {
1930 _test_script_times_on_disk();
1931 _update_modified_scripts_for_external_editor();
1932 }
1933 } break;
1934 }
1935 }
1936
1937 void ScriptEditor::_close_builtin_scripts_from_scene(const String &p_scene) {
1938 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1939 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1940
1941 if (se) {
1942 Ref<Script> scr = se->get_edited_resource();
1943 if (scr.is_null()) {
1944 continue;
1945 }
1946
1947 if (scr->is_built_in() && scr->get_path().begins_with(p_scene)) { // Is an internal script and belongs to scene being closed.
1948 _close_tab(i, false);
1949 i--;
1950 }
1951 }
1952 }
1953 }
1954
1955 void ScriptEditor::edited_scene_changed() {
1956 _update_modified_scripts_for_external_editor();
1957 }
1958
1959 void ScriptEditor::notify_script_close(const Ref<Script> &p_script) {
1960 emit_signal(SNAME("script_close"), p_script);
1961 }
1962
1963 void ScriptEditor::notify_script_changed(const Ref<Script> &p_script) {
1964 emit_signal(SNAME("editor_script_changed"), p_script);
1965 }
1966
1967 Vector<String> ScriptEditor::_get_breakpoints() {
1968 Vector<String> ret;
1969 HashSet<String> loaded_scripts;
1970 for (int i = 0; i < tab_container->get_tab_count(); i++) {
1971 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
1972 if (!se) {
1973 continue;
1974 }
1975
1976 Ref<Script> scr = se->get_edited_resource();
1977 if (scr.is_null()) {
1978 continue;
1979 }
1980
1981 String base = scr->get_path();
1982 loaded_scripts.insert(base);
1983 if (base.is_empty() || base.begins_with("local://")) {
1984 continue;
1985 }
1986
1987 PackedInt32Array bpoints = se->get_breakpoints();
1988 for (int32_t bpoint : bpoints) {
1989 ret.push_back(base + ":" + itos((int)bpoint + 1));
1990 }
1991 }
1992
1993 // Load breakpoints that are in closed scripts.
1994 Vector<String> cached_editors = script_editor_cache->get_sections();
1995 for (const String &E : cached_editors) {
1996 if (loaded_scripts.has(E)) {
1997 continue;
1998 }
1999
2000 Array breakpoints = _get_cached_breakpoints_for_script(E);
2001 for (int breakpoint : breakpoints) {
2002 ret.push_back(E + ":" + itos((int)breakpoint + 1));
2003 }
2004 }
2005 return ret;
2006 }
2007
2008 void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) {
2009 HashSet<String> loaded_scripts;
2010 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2011 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2012 if (!se) {
2013 continue;
2014 }
2015
2016 Ref<Script> scr = se->get_edited_resource();
2017 if (scr.is_null()) {
2018 continue;
2019 }
2020
2021 String base = scr->get_path();
2022 loaded_scripts.insert(base);
2023 if (base.is_empty() || base.begins_with("local://")) {
2024 continue;
2025 }
2026
2027 PackedInt32Array bpoints = se->get_breakpoints();
2028 for (int32_t bpoint : bpoints) {
2029 p_breakpoints->push_back(base + ":" + itos((int)bpoint + 1));
2030 }
2031 }
2032
2033 // Load breakpoints that are in closed scripts.
2034 Vector<String> cached_editors = script_editor_cache->get_sections();
2035 for (const String &E : cached_editors) {
2036 if (loaded_scripts.has(E)) {
2037 continue;
2038 }
2039
2040 Array breakpoints = _get_cached_breakpoints_for_script(E);
2041 for (int breakpoint : breakpoints) {
2042 p_breakpoints->push_back(E + ":" + itos((int)breakpoint + 1));
2043 }
2044 }
2045 }
2046
2047 void ScriptEditor::_members_overview_selected(int p_idx) {
2048 int line = members_overview->get_item_metadata(p_idx);
2049 ScriptEditorBase *current = _get_current_editor();
2050 if (ScriptTextEditor *script_text_editor = Object::cast_to<ScriptTextEditor>(current)) {
2051 script_text_editor->goto_line_centered(line);
2052 } else if (current) {
2053 current->goto_line(line);
2054 }
2055 }
2056
2057 void ScriptEditor::_help_overview_selected(int p_idx) {
2058 Node *current = tab_container->get_tab_control(tab_container->get_current_tab());
2059 EditorHelp *se = Object::cast_to<EditorHelp>(current);
2060 if (!se) {
2061 return;
2062 }
2063 se->scroll_to_section(help_overview->get_item_metadata(p_idx));
2064 }
2065
2066 void ScriptEditor::_script_selected(int p_idx) {
2067 grab_focus_block = !Input::get_singleton()->is_mouse_button_pressed(MouseButton::LEFT); //amazing hack, simply amazing
2068
2069 _go_to_tab(script_list->get_item_metadata(p_idx));
2070 script_name_label->set_text(script_list->get_item_text(p_idx));
2071 grab_focus_block = false;
2072 }
2073
2074 void ScriptEditor::ensure_select_current() {
2075 if (tab_container->get_tab_count() && tab_container->get_current_tab() >= 0) {
2076 ScriptEditorBase *se = _get_current_editor();
2077 if (se) {
2078 se->enable_editor(this);
2079
2080 if (!grab_focus_block && is_visible_in_tree()) {
2081 se->ensure_focus();
2082 }
2083 }
2084 }
2085 _update_find_replace_bar();
2086
2087 _update_selected_editor_menu();
2088 }
2089
2090 bool ScriptEditor::is_editor_floating() {
2091 return is_floating;
2092 }
2093
2094 void ScriptEditor::_find_scripts(Node *p_base, Node *p_current, HashSet<Ref<Script>> &used) {
2095 if (p_current != p_base && p_current->get_owner() != p_base) {
2096 return;
2097 }
2098
2099 if (p_current->get_script_instance()) {
2100 Ref<Script> scr = p_current->get_script();
2101 if (scr.is_valid()) {
2102 used.insert(scr);
2103 }
2104 }
2105
2106 for (int i = 0; i < p_current->get_child_count(); i++) {
2107 _find_scripts(p_base, p_current->get_child(i), used);
2108 }
2109 }
2110
2111 struct _ScriptEditorItemData {
2112 String name;
2113 String sort_key;
2114 Ref<Texture2D> icon;
2115 bool tool = false;
2116 int index = 0;
2117 String tooltip;
2118 bool used = false;
2119 int category = 0;
2120 Node *ref = nullptr;
2121
2122 bool operator<(const _ScriptEditorItemData &id) const {
2123 if (category == id.category) {
2124 if (sort_key == id.sort_key) {
2125 return index < id.index;
2126 } else {
2127 return sort_key.filenocasecmp_to(id.sort_key) < 0;
2128 }
2129 } else {
2130 return category < id.category;
2131 }
2132 }
2133 };
2134
2135 void ScriptEditor::_update_members_overview_visibility() {
2136 ScriptEditorBase *se = _get_current_editor();
2137 if (!se) {
2138 members_overview_alphabeta_sort_button->set_visible(false);
2139 members_overview->set_visible(false);
2140
2141 Node *current = tab_container->get_tab_control(tab_container->get_current_tab());
2142 EditorHelp *editor_help = Object::cast_to<EditorHelp>(current);
2143 overview_vbox->set_visible(help_overview_enabled && editor_help);
2144 return;
2145 }
2146
2147 if (members_overview_enabled && se->show_members_overview()) {
2148 members_overview_alphabeta_sort_button->set_visible(true);
2149 filter_methods->set_visible(true);
2150 members_overview->set_visible(true);
2151 overview_vbox->set_visible(true);
2152 } else {
2153 members_overview_alphabeta_sort_button->set_visible(false);
2154 filter_methods->set_visible(false);
2155 members_overview->set_visible(false);
2156 overview_vbox->set_visible(false);
2157 }
2158 }
2159
2160 void ScriptEditor::_toggle_members_overview_alpha_sort(bool p_alphabetic_sort) {
2161 EditorSettings::get_singleton()->set("text_editor/script_list/sort_members_outline_alphabetically", p_alphabetic_sort);
2162 _update_members_overview();
2163 }
2164
2165 void ScriptEditor::_update_members_overview() {
2166 members_overview->clear();
2167
2168 ScriptEditorBase *se = _get_current_editor();
2169 if (!se) {
2170 return;
2171 }
2172
2173 Vector<String> functions = se->get_functions();
2174 if (EDITOR_GET("text_editor/script_list/sort_members_outline_alphabetically")) {
2175 functions.sort();
2176 }
2177
2178 String filter = filter_methods->get_text();
2179 if (filter.is_empty()) {
2180 for (int i = 0; i < functions.size(); i++) {
2181 String name = functions[i].get_slicec(':', 0);
2182 members_overview->add_item(name);
2183 members_overview->set_item_metadata(-1, functions[i].get_slicec(':', 1).to_int() - 1);
2184 }
2185 } else {
2186 PackedStringArray search_names;
2187 for (int i = 0; i < functions.size(); i++) {
2188 search_names.append(functions[i].get_slicec(':', 0));
2189 }
2190
2191 Vector<FuzzySearchResult> results;
2192 FuzzySearch fuzzy;
2193 fuzzy.set_query(filter, false);
2194 fuzzy.search_all(search_names, results);
2195
2196 for (const FuzzySearchResult &res : results) {
2197 String name = functions[res.original_index].get_slicec(':', 0);
2198 int line = functions[res.original_index].get_slicec(':', 1).to_int() - 1;
2199 members_overview->add_item(name);
2200 members_overview->set_item_metadata(-1, line);
2201 }
2202 }
2203 }
2204
2205 void ScriptEditor::_update_help_overview_visibility() {
2206 int selected = tab_container->get_current_tab();
2207 if (selected < 0 || selected >= tab_container->get_tab_count()) {
2208 help_overview->set_visible(false);
2209 return;
2210 }
2211
2212 Node *current = tab_container->get_tab_control(tab_container->get_current_tab());
2213 EditorHelp *se = Object::cast_to<EditorHelp>(current);
2214 if (!se) {
2215 help_overview->set_visible(false);
2216 return;
2217 }
2218
2219 if (help_overview_enabled) {
2220 members_overview_alphabeta_sort_button->set_visible(false);
2221 filter_methods->set_visible(false);
2222 help_overview->set_visible(true);
2223 overview_vbox->set_visible(true);
2224 } else {
2225 help_overview->set_visible(false);
2226 overview_vbox->set_visible(false);
2227 }
2228 }
2229
2230 void ScriptEditor::_update_help_overview() {
2231 help_overview->clear();
2232
2233 int selected = tab_container->get_current_tab();
2234 if (selected < 0 || selected >= tab_container->get_tab_count()) {
2235 return;
2236 }
2237
2238 Node *current = tab_container->get_tab_control(tab_container->get_current_tab());
2239 EditorHelp *se = Object::cast_to<EditorHelp>(current);
2240 if (!se) {
2241 return;
2242 }
2243
2244 Vector<Pair<String, int>> sections = se->get_sections();
2245 for (int i = 0; i < sections.size(); i++) {
2246 help_overview->add_item(sections[i].first);
2247 help_overview->set_item_metadata(i, sections[i].second);
2248 }
2249 }
2250
2251 void ScriptEditor::_update_online_doc() {
2252 Node *current = tab_container->get_tab_control(tab_container->get_current_tab());
2253
2254 EditorHelp *eh = Object::cast_to<EditorHelp>(current);
2255 bool native_class_doc = false;
2256 if (eh) {
2257 const HashMap<String, DocData::ClassDoc>::ConstIterator E = EditorHelp::get_doc_data()->class_list.find(eh->get_class());
2258 native_class_doc = E && !E->value.is_script_doc;
2259 }
2260 if (native_class_doc) {
2261 String name = eh->get_class();
2262 String tooltip = vformat(TTR("Open '%s' in Godot online documentation."), name);
2263 site_search->set_text(TTRC("Open in Online Docs"));
2264 site_search->set_tooltip_text(tooltip);
2265 } else {
2266 site_search->set_text(TTRC("Online Docs"));
2267 site_search->set_tooltip_text(TTRC("Open Godot online documentation."));
2268 }
2269 }
2270
2271 void ScriptEditor::_update_script_colors() {
2272 bool script_temperature_enabled = EDITOR_GET("text_editor/script_list/script_temperature_enabled");
2273
2274 int hist_size = EDITOR_GET("text_editor/script_list/script_temperature_history_size");
2275 Color hot_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
2276 hot_color.set_s(hot_color.get_s() * 0.9);
2277 Color cold_color = get_theme_color(SceneStringName(font_color), EditorStringName(Editor));
2278
2279 for (int i = 0; i < script_list->get_item_count(); i++) {
2280 int c = script_list->get_item_metadata(i);
2281 Node *n = tab_container->get_tab_control(c);
2282 if (!n) {
2283 continue;
2284 }
2285
2286 if (script_temperature_enabled) {
2287 int pass = n->get_meta("__editor_pass", -1);
2288 if (pass < 0) {
2289 continue;
2290 }
2291
2292 int h = edit_pass - pass;
2293 if (h > hist_size) {
2294 continue;
2295 }
2296 int non_zero_hist_size = (hist_size == 0) ? 1 : hist_size;
2297 float v = Math::ease((edit_pass - pass) / float(non_zero_hist_size), 0.4);
2298
2299 script_list->set_item_custom_fg_color(i, hot_color.lerp(cold_color, v));
2300 }
2301 }
2302 }
2303
2304 void ScriptEditor::_update_script_names() {
2305 if (restoring_layout) {
2306 return;
2307 }
2308
2309 HashSet<Ref<Script>> used;
2310 Node *edited = EditorNode::get_singleton()->get_edited_scene();
2311 if (edited && EDITOR_GET("text_editor/script_list/highlight_scene_scripts")) {
2312 _find_scripts(edited, edited, used);
2313 }
2314
2315 script_list->clear();
2316 bool split_script_help = EDITOR_GET("text_editor/script_list/group_help_pages");
2317 ScriptSortBy sort_by = (ScriptSortBy)(int)EDITOR_GET("text_editor/script_list/sort_scripts_by");
2318 ScriptListName display_as = (ScriptListName)(int)EDITOR_GET("text_editor/script_list/list_script_names_as");
2319
2320 Vector<_ScriptEditorItemData> sedata;
2321
2322 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2323 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2324 if (se) {
2325 Ref<Texture2D> icon = se->get_theme_icon();
2326 String path = se->get_edited_resource()->get_path();
2327 bool saved = !path.is_empty();
2328 String name = se->get_name();
2329 Ref<Script> scr = se->get_edited_resource();
2330
2331 _ScriptEditorItemData sd;
2332 sd.icon = icon;
2333 sd.name = name;
2334 sd.tooltip = saved ? path : TTR("Unsaved file.");
2335 sd.index = i;
2336 sd.used = used.has(se->get_edited_resource());
2337 sd.category = 0;
2338 sd.ref = se;
2339 if (scr.is_valid()) {
2340 sd.tool = scr->is_tool();
2341 }
2342
2343 switch (sort_by) {
2344 case SORT_BY_NAME: {
2345 sd.sort_key = name.to_lower();
2346 } break;
2347 case SORT_BY_PATH: {
2348 sd.sort_key = path;
2349 } break;
2350 case SORT_BY_NONE: {
2351 sd.sort_key = "";
2352 } break;
2353 }
2354
2355 switch (display_as) {
2356 case DISPLAY_NAME: {
2357 sd.name = name;
2358 } break;
2359 case DISPLAY_DIR_AND_NAME: {
2360 if (!path.get_base_dir().get_file().is_empty()) {
2361 sd.name = path.get_base_dir().get_file().path_join(name);
2362 } else {
2363 sd.name = name;
2364 }
2365 } break;
2366 case DISPLAY_FULL_PATH: {
2367 sd.name = path;
2368 } break;
2369 }
2370 if (!saved) {
2371 sd.name = se->get_name();
2372 }
2373
2374 sedata.push_back(sd);
2375 }
2376
2377 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
2378 if (eh && !eh->get_class().is_empty()) {
2379 String name = eh->get_class().unquote();
2380 Ref<Texture2D> icon = get_editor_theme_icon(SNAME("Help"));
2381 String tooltip = vformat(TTR("%s Class Reference"), name);
2382
2383 _ScriptEditorItemData sd;
2384 sd.icon = icon;
2385 sd.name = name;
2386 sd.sort_key = name.to_lower();
2387 sd.tooltip = tooltip;
2388 sd.index = i;
2389 sd.used = false;
2390 sd.category = split_script_help ? 1 : 0;
2391 sd.ref = eh;
2392
2393 sedata.push_back(sd);
2394 }
2395 }
2396
2397 Vector<String> disambiguated_script_names;
2398 Vector<String> full_script_paths;
2399 for (int j = 0; j < sedata.size(); j++) {
2400 String name = sedata[j].name.replace("(*)", "");
2401 ScriptListName script_display = (ScriptListName)(int)EDITOR_GET("text_editor/script_list/list_script_names_as");
2402 switch (script_display) {
2403 case DISPLAY_NAME: {
2404 name = name.get_file();
2405 } break;
2406 case DISPLAY_DIR_AND_NAME: {
2407 name = name.get_base_dir().get_file().path_join(name.get_file());
2408 } break;
2409 default:
2410 break;
2411 }
2412
2413 disambiguated_script_names.append(name);
2414 full_script_paths.append(sedata[j].tooltip);
2415 }
2416
2417 EditorNode::disambiguate_filenames(full_script_paths, disambiguated_script_names);
2418
2419 for (int j = 0; j < sedata.size(); j++) {
2420 if (sedata[j].name.ends_with("(*)")) {
2421 sedata.write[j].name = disambiguated_script_names[j] + "(*)";
2422 } else {
2423 sedata.write[j].name = disambiguated_script_names[j];
2424 }
2425 }
2426
2427 if (_sort_list_on_update && !sedata.is_empty()) {
2428 sedata.sort();
2429
2430 // change actual order of tab_container so that the order can be rearranged by user
2431 int cur_tab = tab_container->get_current_tab();
2432 int prev_tab = tab_container->get_previous_tab();
2433 int new_cur_tab = -1;
2434 int new_prev_tab = -1;
2435 for (int i = 0; i < sedata.size(); i++) {
2436 tab_container->move_child(sedata[i].ref, i);
2437 if (new_prev_tab == -1 && sedata[i].index == prev_tab) {
2438 new_prev_tab = i;
2439 }
2440 if (new_cur_tab == -1 && sedata[i].index == cur_tab) {
2441 new_cur_tab = i;
2442 }
2443 // Update index of sd entries for sorted order
2444 _ScriptEditorItemData sd = sedata[i];
2445 sd.index = i;
2446 sedata.set(i, sd);
2447 }
2448
2449 lock_history = true;
2450 _go_to_tab(new_prev_tab);
2451 _go_to_tab(new_cur_tab);
2452 lock_history = false;
2453 _sort_list_on_update = false;
2454 }
2455
2456 Vector<_ScriptEditorItemData> sedata_filtered;
2457
2458 String filter = filter_scripts->get_text();
2459
2460 if (filter.is_empty()) {
2461 sedata_filtered = sedata;
2462 } else {
2463 PackedStringArray search_names;
2464 for (int i = 0; i < sedata.size(); i++) {
2465 search_names.append(sedata[i].name);
2466 }
2467
2468 Vector<FuzzySearchResult> results;
2469 FuzzySearch fuzzy;
2470 fuzzy.set_query(filter, false);
2471 fuzzy.search_all(search_names, results);
2472
2473 for (const FuzzySearchResult &res : results) {
2474 sedata_filtered.push_back(sedata[res.original_index]);
2475 }
2476 }
2477
2478 Color tool_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
2479 tool_color.set_s(tool_color.get_s() * 1.5);
2480 for (int i = 0; i < sedata_filtered.size(); i++) {
2481 script_list->add_item(sedata_filtered[i].name, sedata_filtered[i].icon);
2482 if (sedata_filtered[i].tool) {
2483 script_list->set_item_icon_modulate(-1, tool_color);
2484 }
2485
2486 int index = script_list->get_item_count() - 1;
2487 script_list->set_item_tooltip(index, sedata_filtered[i].tooltip);
2488 script_list->set_item_metadata(index, sedata_filtered[i].index); /* Saving as metadata the script's index in the tab container and not the filtered one */
2489 if (sedata_filtered[i].used) {
2490 script_list->set_item_custom_bg_color(index, Color(.5, .5, .5, .125));
2491 }
2492 if (tab_container->get_current_tab() == sedata_filtered[i].index) {
2493 script_list->select(index);
2494
2495 script_name_label->set_text(sedata_filtered[i].name);
2496
2497 ScriptEditorBase *se = _get_current_editor();
2498 if (se) {
2499 se->enable_editor(this);
2500 _update_selected_editor_menu();
2501 }
2502 }
2503 }
2504
2505 if (!waiting_update_names) {
2506 _update_members_overview();
2507 _update_help_overview();
2508 } else {
2509 waiting_update_names = false;
2510 }
2511 _update_members_overview_visibility();
2512 _update_help_overview_visibility();
2513 _update_script_colors();
2514 }
2515
2516 Ref<TextFile> ScriptEditor::_load_text_file(const String &p_path, Error *r_error) const {
2517 if (r_error) {
2518 *r_error = ERR_FILE_CANT_OPEN;
2519 }
2520
2521 String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
2522 String path = ResourceLoader::path_remap(local_path);
2523
2524 TextFile *text_file = memnew(TextFile);
2525 Ref<TextFile> text_res(text_file);
2526 Error err = text_file->load_text(path);
2527
2528 ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot load text file '" + path + "'.");
2529
2530 text_file->set_file_path(local_path);
2531 text_file->set_path(local_path, true);
2532
2533 if (ResourceLoader::get_timestamp_on_load()) {
2534 text_file->set_last_modified_time(FileAccess::get_modified_time(path));
2535 }
2536
2537 if (r_error) {
2538 *r_error = OK;
2539 }
2540
2541 return text_res;
2542 }
2543
2544 Error ScriptEditor::_save_text_file(Ref<TextFile> p_text_file, const String &p_path) {
2545 Ref<TextFile> sqscr = p_text_file;
2546 ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
2547
2548 String source = sqscr->get_text();
2549
2550 Error err;
2551 {
2552 Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
2553
2554 ERR_FAIL_COND_V_MSG(err, err, "Cannot save text file '" + p_path + "'.");
2555
2556 file->store_string(source);
2557 if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
2558 return ERR_CANT_CREATE;
2559 }
2560 }
2561
2562 if (ResourceSaver::get_timestamp_on_save()) {
2563 p_text_file->set_last_modified_time(FileAccess::get_modified_time(p_path));
2564 }
2565
2566 EditorFileSystem::get_singleton()->update_file(p_path);
2567
2568 _res_saved_callback(sqscr);
2569 return OK;
2570 }
2571
2572 bool ScriptEditor::edit(const Ref<Resource> &p_resource, int p_line, int p_col, bool p_grab_focus) {
2573 if (p_resource.is_null()) {
2574 return false;
2575 }
2576
2577 Ref<Script> scr = p_resource;
2578
2579 // Don't open dominant script if using an external editor.
2580 bool use_external_editor =
2581 external_editor_active ||
2582 (scr.is_valid() && scr->get_language()->overrides_external_editor());
2583 use_external_editor = use_external_editor && !(scr.is_valid() && scr->is_built_in()); // Ignore external editor for built-in scripts.
2584 const bool open_dominant = EDITOR_GET("text_editor/behavior/files/open_dominant_script_on_scene_change");
2585
2586 const bool should_open = (open_dominant && !use_external_editor) || !EditorNode::get_singleton()->is_changing_scene();
2587
2588 if (scr.is_valid() && scr->get_language()->overrides_external_editor()) {
2589 if (should_open) {
2590 Error err = scr->get_language()->open_in_external_editor(scr, p_line >= 0 ? p_line : 0, p_col);
2591 if (err != OK) {
2592 ERR_PRINT("Couldn't open script in the overridden external text editor");
2593 }
2594 }
2595 return false;
2596 }
2597
2598 if (use_external_editor &&
2599 (EditorDebuggerNode::get_singleton()->get_dump_stack_script() != p_resource || EditorDebuggerNode::get_singleton()->get_debug_with_external_editor()) &&
2600 p_resource->get_path().is_resource_file()) {
2601 if (ScriptEditorPlugin::open_in_external_editor(ProjectSettings::get_singleton()->globalize_path(p_resource->get_path()), p_line, p_col)) {
2602 return false;
2603 } else {
2604 ERR_PRINT("Couldn't open external text editor, falling back to the internal editor. Review your `text_editor/external/` editor settings.");
2605 }
2606 }
2607
2608 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2609 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2610 if (!se) {
2611 continue;
2612 }
2613
2614 if ((scr.is_valid() && se->get_edited_resource() == p_resource) || se->get_edited_resource()->get_path() == p_resource->get_path()) {
2615 if (should_open) {
2616 se->enable_editor(this);
2617
2618 if (tab_container->get_current_tab() != i) {
2619 _go_to_tab(i);
2620 }
2621 if (is_visible_in_tree()) {
2622 se->ensure_focus();
2623 }
2624
2625 if (p_line >= 0) {
2626 se->goto_line(p_line, p_col);
2627 }
2628 }
2629 _update_script_names();
2630 script_list->ensure_current_is_visible();
2631 return true;
2632 }
2633 }
2634
2635 // doesn't have it, make a new one
2636
2637 ScriptEditorBase *se = nullptr;
2638
2639 for (int i = script_editor_func_count - 1; i >= 0; i--) {
2640 se = script_editor_funcs[i](p_resource);
2641 if (se) {
2642 break;
2643 }
2644 }
2645 ERR_FAIL_NULL_V(se, false);
2646
2647 se->set_edited_resource(p_resource);
2648
2649 // Syntax highlighting.
2650 bool highlighter_set = false;
2651 for (int i = 0; i < syntax_highlighters.size(); i++) {
2652 Ref<EditorSyntaxHighlighter> highlighter = syntax_highlighters[i]->_create();
2653 if (highlighter.is_null()) {
2654 continue;
2655 }
2656 se->add_syntax_highlighter(highlighter);
2657
2658 if (highlighter_set) {
2659 continue;
2660 }
2661
2662 PackedStringArray languages = highlighter->_get_supported_languages();
2663 // If script try language, else use extension.
2664 if (scr.is_valid()) {
2665 if (languages.has(scr->get_language()->get_name())) {
2666 se->set_syntax_highlighter(highlighter);
2667 highlighter_set = true;
2668 }
2669 continue;
2670 }
2671
2672 if (languages.has(p_resource->get_path().get_extension())) {
2673 se->set_syntax_highlighter(highlighter);
2674 highlighter_set = true;
2675 }
2676 }
2677
2678 tab_container->add_child(se);
2679
2680 if (p_grab_focus) {
2681 se->enable_editor(this);
2682 }
2683
2684 // If we delete a script within the filesystem, the original resource path
2685 // is lost, so keep it as `edited_file_data` to figure out the exact tab to delete.
2686 se->edited_file_data.path = p_resource->get_path();
2687 se->edited_file_data.last_modified_time = FileAccess::get_modified_time(p_resource->get_path());
2688
2689 se->set_tooltip_request_func(callable_mp(this, &ScriptEditor::_get_debug_tooltip));
2690
2691 if (se->get_edit_menu()) {
2692 se->get_edit_menu()->hide();
2693 menu_hb->add_child(se->get_edit_menu());
2694 menu_hb->move_child(se->get_edit_menu(), 1);
2695 }
2696
2697 if (p_grab_focus) {
2698 _go_to_tab(tab_container->get_tab_count() - 1);
2699 _add_recent_script(p_resource->get_path());
2700 }
2701
2702 if (script_editor_cache->has_section(p_resource->get_path())) {
2703 se->set_edit_state(script_editor_cache->get_value(p_resource->get_path(), "state"));
2704 ScriptTextEditor *ste = Object::cast_to<ScriptTextEditor>(se);
2705 if (ste) {
2706 ste->store_previous_state();
2707 }
2708 }
2709
2710 _sort_list_on_update = true;
2711 _update_script_names();
2712 _save_layout();
2713 se->connect("name_changed", callable_mp(this, &ScriptEditor::_update_script_names));
2714 se->connect("edited_script_changed", callable_mp(this, &ScriptEditor::_script_changed));
2715 se->connect("request_help", callable_mp(this, &ScriptEditor::_help_search));
2716 se->connect("request_open_script_at_line", callable_mp(this, &ScriptEditor::_goto_script_line));
2717 se->connect("go_to_help", callable_mp(this, &ScriptEditor::_help_class_goto));
2718 se->connect("request_save_history", callable_mp(this, &ScriptEditor::_save_history));
2719 se->connect("request_save_previous_state", callable_mp(this, &ScriptEditor::_save_previous_state));
2720 se->connect("search_in_files_requested", callable_mp(this, &ScriptEditor::open_find_in_files_dialog));
2721 se->connect("replace_in_files_requested", callable_mp(this, &ScriptEditor::_on_replace_in_files_requested));
2722 se->connect("go_to_method", callable_mp(this, &ScriptEditor::script_goto_method));
2723
2724 CodeTextEditor *cte = se->get_code_editor();
2725 if (cte) {
2726 cte->set_zoom_factor(zoom_factor);
2727 cte->connect("zoomed", callable_mp(this, &ScriptEditor::_set_script_zoom_factor));
2728 cte->connect(SceneStringName(visibility_changed), callable_mp(this, &ScriptEditor::_update_code_editor_zoom_factor).bind(cte));
2729 }
2730
2731 //test for modification, maybe the script was not edited but was loaded
2732
2733 _test_script_times_on_disk(p_resource);
2734 _update_modified_scripts_for_external_editor(p_resource);
2735
2736 if (p_line >= 0) {
2737 se->goto_line(p_line, p_col);
2738 }
2739
2740 notify_script_changed(p_resource);
2741 return true;
2742 }
2743
2744 PackedStringArray ScriptEditor::get_unsaved_scripts() const {
2745 PackedStringArray unsaved_list;
2746
2747 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2748 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2749 if (se && se->is_unsaved()) {
2750 unsaved_list.append(se->get_name());
2751 }
2752 }
2753 return unsaved_list;
2754 }
2755
2756 void ScriptEditor::save_current_script() {
2757 ScriptEditorBase *current = _get_current_editor();
2758 if (!current || _test_script_times_on_disk()) {
2759 return;
2760 }
2761
2762 if (trim_trailing_whitespace_on_save) {
2763 current->trim_trailing_whitespace();
2764 }
2765
2766 if (trim_final_newlines_on_save) {
2767 current->trim_final_newlines();
2768 }
2769
2770 if (convert_indent_on_save) {
2771 current->convert_indent();
2772 }
2773
2774 Ref<Resource> resource = current->get_edited_resource();
2775 Ref<TextFile> text_file = resource;
2776 Ref<Script> scr = resource;
2777
2778 if (text_file.is_valid()) {
2779 current->apply_code();
2780 _save_text_file(text_file, text_file->get_path());
2781 return;
2782 }
2783
2784 if (scr.is_valid()) {
2785 clear_docs_from_script(scr);
2786 }
2787
2788 EditorNode::get_singleton()->save_resource(resource);
2789
2790 if (scr.is_valid()) {
2791 update_docs_from_script(scr);
2792 }
2793 }
2794
2795 void ScriptEditor::save_all_scripts() {
2796 HashSet<String> scenes_to_save;
2797
2798 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2799 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2800 if (!se) {
2801 continue;
2802 }
2803
2804 if (convert_indent_on_save) {
2805 se->convert_indent();
2806 }
2807
2808 if (trim_trailing_whitespace_on_save) {
2809 se->trim_trailing_whitespace();
2810 }
2811
2812 if (trim_final_newlines_on_save) {
2813 se->trim_final_newlines();
2814 }
2815
2816 if (!se->is_unsaved()) {
2817 continue;
2818 }
2819
2820 Ref<Resource> edited_res = se->get_edited_resource();
2821 if (edited_res.is_valid()) {
2822 se->apply_code();
2823 }
2824
2825 Ref<Script> scr = edited_res;
2826
2827 if (scr.is_valid()) {
2828 clear_docs_from_script(scr);
2829 }
2830
2831 if (!edited_res->is_built_in()) {
2832 Ref<TextFile> text_file = edited_res;
2833 if (text_file.is_valid()) {
2834 _save_text_file(text_file, text_file->get_path());
2835 continue;
2836 }
2837
2838 // External script, save it.
2839 EditorNode::get_singleton()->save_resource(edited_res);
2840 } else {
2841 // For built-in scripts, save their scenes instead.
2842 const String scene_path = edited_res->get_path().get_slice("::", 0);
2843 if (!scene_path.is_empty() && !scenes_to_save.has(scene_path)) {
2844 scenes_to_save.insert(scene_path);
2845 }
2846 }
2847
2848 if (scr.is_valid()) {
2849 update_docs_from_script(scr);
2850 }
2851 }
2852
2853 if (!scenes_to_save.is_empty()) {
2854 EditorNode::get_singleton()->save_scene_list(scenes_to_save);
2855 }
2856
2857 _update_script_names();
2858 }
2859
2860 void ScriptEditor::update_script_times() {
2861 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2862 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2863 if (se) {
2864 se->edited_file_data.last_modified_time = FileAccess::get_modified_time(se->edited_file_data.path);
2865 }
2866 }
2867 }
2868
2869 void ScriptEditor::apply_scripts() const {
2870 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2871 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2872 if (!se) {
2873 continue;
2874 }
2875 se->insert_final_newline();
2876 se->apply_code();
2877 }
2878 }
2879
2880 void ScriptEditor::reload_scripts(bool p_refresh_only) {
2881 // Call deferred to make sure it runs on the main thread.
2882 if (!Thread::is_main_thread()) {
2883 callable_mp(this, &ScriptEditor::_reload_scripts).call_deferred(p_refresh_only);
2884 return;
2885 }
2886 _reload_scripts(p_refresh_only);
2887 }
2888
2889 void ScriptEditor::_reload_scripts(bool p_refresh_only) {
2890 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2891 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2892 if (!se) {
2893 continue;
2894 }
2895
2896 Ref<Resource> edited_res = se->get_edited_resource();
2897
2898 if (edited_res->is_built_in()) {
2899 continue; // Internal script, who cares.
2900 }
2901
2902 if (p_refresh_only) {
2903 // Make sure the modified time is correct.
2904 se->edited_file_data.last_modified_time = FileAccess::get_modified_time(edited_res->get_path());
2905 } else {
2906 uint64_t last_date = se->edited_file_data.last_modified_time;
2907 uint64_t date = FileAccess::get_modified_time(edited_res->get_path());
2908
2909 if (last_date == date) {
2910 continue;
2911 }
2912 se->edited_file_data.last_modified_time = date;
2913
2914 Ref<Script> scr = edited_res;
2915 if (scr.is_valid()) {
2916 Ref<Script> rel_scr = ResourceLoader::load(scr->get_path(), scr->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
2917 ERR_CONTINUE(rel_scr.is_null());
2918 scr->set_source_code(rel_scr->get_source_code());
2919 scr->reload(true);
2920
2921 update_docs_from_script(scr);
2922 }
2923
2924 Ref<JSON> json = edited_res;
2925 if (json.is_valid()) {
2926 Ref<JSON> rel_json = ResourceLoader::load(json->get_path(), json->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
2927 ERR_CONTINUE(rel_json.is_null());
2928 json->parse(rel_json->get_parsed_text(), true);
2929 }
2930
2931 Ref<TextFile> text_file = edited_res;
2932 if (text_file.is_valid()) {
2933 text_file->reload_from_file();
2934 }
2935 }
2936
2937 se->reload_text();
2938 }
2939
2940 disk_changed->hide();
2941 _update_script_names();
2942 }
2943
2944 void ScriptEditor::open_find_in_files_dialog(const String &text) {
2945 find_in_files_dialog->set_find_in_files_mode(FindInFilesDialog::SEARCH_MODE);
2946 find_in_files_dialog->set_search_text(text);
2947 find_in_files_dialog->popup_centered();
2948 }
2949
2950 void ScriptEditor::open_script_create_dialog(const String &p_base_name, const String &p_base_path) {
2951 _menu_option(FILE_MENU_NEW);
2952 script_create_dialog->config(p_base_name, p_base_path);
2953 }
2954
2955 void ScriptEditor::open_text_file_create_dialog(const String &p_base_path, const String &p_base_name) {
2956 _menu_option(FILE_MENU_NEW_TEXTFILE);
2957 file_dialog->set_current_dir(p_base_path);
2958 file_dialog->set_current_file(p_base_name);
2959 }
2960
2961 Ref<Resource> ScriptEditor::open_file(const String &p_file) {
2962 List<String> extensions;
2963 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
2964 ResourceLoader::get_recognized_extensions_for_type("JSON", &extensions);
2965 if (extensions.find(p_file.get_extension())) {
2966 Ref<Resource> scr = ResourceLoader::load(p_file);
2967 if (scr.is_null()) {
2968 EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + p_file, TTR("Error!"));
2969 return Ref<Resource>();
2970 }
2971
2972 edit(scr);
2973 return scr;
2974 }
2975
2976 Error error;
2977 Ref<TextFile> text_file = _load_text_file(p_file, &error);
2978 if (error != OK) {
2979 EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + p_file, TTR("Error!"));
2980 return Ref<Resource>();
2981 }
2982
2983 if (text_file.is_valid()) {
2984 edit(text_file);
2985 return text_file;
2986 }
2987 return Ref<Resource>();
2988 }
2989
2990 void ScriptEditor::_editor_stop() {
2991 for (int i = 0; i < tab_container->get_tab_count(); i++) {
2992 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
2993 if (!se) {
2994 continue;
2995 }
2996
2997 se->set_debugger_active(false);
2998 }
2999 }
3000
3001 void ScriptEditor::_add_callback(Object *p_obj, const String &p_function, const PackedStringArray &p_args) {
3002 ERR_FAIL_NULL(p_obj);
3003 Ref<Script> scr = p_obj->get_script();
3004 ERR_FAIL_COND(scr.is_null());
3005
3006 if (!scr->get_language()->can_make_function()) {
3007 return;
3008 }
3009
3010 EditorNode::get_singleton()->push_item(scr.ptr());
3011
3012 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3013 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3014 if (!se) {
3015 continue;
3016 }
3017 if (se->get_edited_resource() != scr) {
3018 continue;
3019 }
3020
3021 se->add_callback(p_function, p_args);
3022
3023 _go_to_tab(i);
3024
3025 script_list->select(script_list->find_metadata(i));
3026
3027 // Save the current script so the changes can be picked up by an external editor.
3028 if (!scr.ptr()->is_built_in()) { // But only if it's not built-in script.
3029 save_current_script();
3030 }
3031
3032 break;
3033 }
3034
3035 // Move back to the previously edited node to reselect it in the Inspector and the SignalsDock.
3036 // We assume that the previous item is the node on which the callbacks were added.
3037 EditorNode::get_singleton()->edit_previous_item();
3038 }
3039
3040 void ScriptEditor::_save_editor_state(ScriptEditorBase *p_editor) {
3041 if (restoring_layout) {
3042 return;
3043 }
3044
3045 const String &path = p_editor->get_edited_resource()->get_path();
3046 if (path.is_empty()) {
3047 return;
3048 }
3049
3050 script_editor_cache->set_value(path, "state", p_editor->get_edit_state());
3051 // This is saved later when we save the editor layout.
3052 }
3053
3054 void ScriptEditor::_save_layout() {
3055 if (restoring_layout) {
3056 return;
3057 }
3058
3059 EditorNode::get_singleton()->save_editor_layout_delayed();
3060 }
3061
3062 void ScriptEditor::_apply_editor_settings() {
3063 textfile_extensions.clear();
3064 const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
3065 for (const String &E : textfile_ext) {
3066 textfile_extensions.insert(E);
3067 }
3068
3069 trim_trailing_whitespace_on_save = EDITOR_GET("text_editor/behavior/files/trim_trailing_whitespace_on_save");
3070 trim_final_newlines_on_save = EDITOR_GET("text_editor/behavior/files/trim_final_newlines_on_save");
3071 convert_indent_on_save = EDITOR_GET("text_editor/behavior/files/convert_indent_on_save");
3072
3073 members_overview_enabled = EDITOR_GET("text_editor/script_list/show_members_overview");
3074 help_overview_enabled = EDITOR_GET("text_editor/help/show_help_index");
3075 external_editor_active = EDITOR_GET("text_editor/external/use_external_editor");
3076 _update_members_overview_visibility();
3077 _update_help_overview_visibility();
3078
3079 _update_autosave_timer();
3080
3081 _update_script_names();
3082
3083 ScriptServer::set_reload_scripts_on_save(EDITOR_GET("text_editor/behavior/files/auto_reload_and_parse_scripts_on_save"));
3084
3085 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3086 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3087 if (!se) {
3088 continue;
3089 }
3090
3091 se->update_settings();
3092 }
3093 }
3094
3095 void ScriptEditor::_filesystem_changed() {
3096 _update_script_names();
3097 }
3098
3099 void ScriptEditor::_files_moved(const String &p_old_file, const String &p_new_file) {
3100 if (!script_editor_cache->has_section(p_old_file)) {
3101 return;
3102 }
3103
3104 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3105 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3106 if (se && se->edited_file_data.path == p_old_file) {
3107 se->edited_file_data.path = p_new_file;
3108 break;
3109 }
3110 }
3111
3112 Variant state = script_editor_cache->get_value(p_old_file, "state");
3113 script_editor_cache->erase_section(p_old_file);
3114 script_editor_cache->set_value(p_new_file, "state", state);
3115
3116 // If Script, update breakpoints with debugger.
3117 Array breakpoints = _get_cached_breakpoints_for_script(p_new_file);
3118 for (int breakpoint : breakpoints) {
3119 int line = (int)breakpoint + 1;
3120 EditorDebuggerNode::get_singleton()->set_breakpoint(p_old_file, line, false);
3121 if (!p_new_file.begins_with("local://") && ResourceLoader::exists(p_new_file, "Script")) {
3122 EditorDebuggerNode::get_singleton()->set_breakpoint(p_new_file, line, true);
3123 }
3124 }
3125 // This is saved later when we save the editor layout.
3126 }
3127
3128 void ScriptEditor::_file_removed(const String &p_removed_file) {
3129 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3130 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3131 if (!se) {
3132 continue;
3133 }
3134 if (se->edited_file_data.path == p_removed_file) {
3135 // The script is deleted with no undo, so just close the tab.
3136 _close_tab(i, false, false);
3137 }
3138 }
3139
3140 // Check closed.
3141 if (script_editor_cache->has_section(p_removed_file)) {
3142 Array breakpoints = _get_cached_breakpoints_for_script(p_removed_file);
3143 for (int breakpoint : breakpoints) {
3144 EditorDebuggerNode::get_singleton()->set_breakpoint(p_removed_file, (int)breakpoint + 1, false);
3145 }
3146 script_editor_cache->erase_section(p_removed_file);
3147 }
3148 }
3149
3150 void ScriptEditor::_update_find_replace_bar() {
3151 ScriptEditorBase *se = _get_current_editor();
3152 if (se) {
3153 se->set_find_replace_bar(find_replace_bar);
3154 } else {
3155 find_replace_bar->set_text_edit(nullptr);
3156 find_replace_bar->hide();
3157 }
3158 }
3159
3160 void ScriptEditor::_autosave_scripts() {
3161 save_all_scripts();
3162 }
3163
3164 void ScriptEditor::_update_autosave_timer() {
3165 if (!autosave_timer->is_inside_tree()) {
3166 return;
3167 }
3168
3169 float autosave_time = EDITOR_GET("text_editor/behavior/files/autosave_interval_secs");
3170 if (autosave_time > 0) {
3171 autosave_timer->set_wait_time(autosave_time);
3172 autosave_timer->start();
3173 } else {
3174 autosave_timer->stop();
3175 }
3176 }
3177
3178 void ScriptEditor::_tree_changed() {
3179 if (waiting_update_names) {
3180 return;
3181 }
3182
3183 waiting_update_names = true;
3184 callable_mp(this, &ScriptEditor::_update_script_names).call_deferred();
3185 }
3186
3187 void ScriptEditor::_split_dragged(float) {
3188 _save_layout();
3189 }
3190
3191 Variant ScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
3192 if (tab_container->get_tab_count() == 0) {
3193 return Variant();
3194 }
3195
3196 Node *cur_node = tab_container->get_tab_control(tab_container->get_current_tab());
3197
3198 HBoxContainer *drag_preview = memnew(HBoxContainer);
3199 String preview_name = "";
3200 Ref<Texture2D> preview_icon;
3201
3202 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(cur_node);
3203 if (se) {
3204 preview_name = se->get_name();
3205 preview_icon = se->get_theme_icon();
3206 }
3207 EditorHelp *eh = Object::cast_to<EditorHelp>(cur_node);
3208 if (eh) {
3209 preview_name = eh->get_class();
3210 preview_icon = get_editor_theme_icon(SNAME("Help"));
3211 }
3212
3213 if (preview_icon.is_valid()) {
3214 TextureRect *tf = memnew(TextureRect);
3215 tf->set_texture(preview_icon);
3216 tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
3217 drag_preview->add_child(tf);
3218 }
3219 Label *label = memnew(Label(preview_name));
3220 label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED); // Don't translate script names and class names.
3221 drag_preview->add_child(label);
3222 set_drag_preview(drag_preview);
3223
3224 Dictionary drag_data;
3225 drag_data["type"] = "script_list_element"; // using a custom type because node caused problems when dragging to scene tree
3226 drag_data["script_list_element"] = cur_node;
3227
3228 return drag_data;
3229 }
3230
3231 bool ScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
3232 Dictionary d = p_data;
3233 if (!d.has("type")) {
3234 return false;
3235 }
3236
3237 if (String(d["type"]) == "script_list_element") {
3238 Node *node = Object::cast_to<Node>(d["script_list_element"]);
3239
3240 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(node);
3241 if (se) {
3242 return true;
3243 }
3244 EditorHelp *eh = Object::cast_to<EditorHelp>(node);
3245 if (eh) {
3246 return true;
3247 }
3248 }
3249
3250 if (String(d["type"]) == "nodes") {
3251 Array nodes = d["nodes"];
3252 if (nodes.is_empty()) {
3253 return false;
3254 }
3255 Node *node = get_node((nodes[0]));
3256
3257 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(node);
3258 if (se) {
3259 return true;
3260 }
3261 EditorHelp *eh = Object::cast_to<EditorHelp>(node);
3262 if (eh) {
3263 return true;
3264 }
3265 }
3266
3267 if (String(d["type"]) == "files") {
3268 Vector<String> files = d["files"];
3269
3270 if (files.is_empty()) {
3271 return false; //weird
3272 }
3273
3274 for (int i = 0; i < files.size(); i++) {
3275 const String &file = files[i];
3276 if (file.is_empty() || !FileAccess::exists(file)) {
3277 continue;
3278 }
3279 if (ResourceLoader::exists(file, "Script") || ResourceLoader::exists(file, "JSON")) {
3280 Ref<Resource> scr = ResourceLoader::load(file);
3281 if (scr.is_valid()) {
3282 return true;
3283 }
3284 }
3285
3286 if (textfile_extensions.has(file.get_extension())) {
3287 Error err;
3288 Ref<TextFile> text_file = _load_text_file(file, &err);
3289 if (text_file.is_valid() && err == OK) {
3290 return true;
3291 }
3292 }
3293 }
3294 return false;
3295 }
3296
3297 return false;
3298 }
3299
3300 void ScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
3301 if (!can_drop_data_fw(p_point, p_data, p_from)) {
3302 return;
3303 }
3304
3305 Dictionary d = p_data;
3306 if (!d.has("type")) {
3307 return;
3308 }
3309
3310 if (String(d["type"]) == "script_list_element") {
3311 Node *node = Object::cast_to<Node>(d["script_list_element"]);
3312
3313 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(node);
3314 EditorHelp *eh = Object::cast_to<EditorHelp>(node);
3315 if (se || eh) {
3316 int new_index = 0;
3317 if (script_list->get_item_count() > 0) {
3318 int pos = 0;
3319 if (p_point == Vector2(Math::INF, Math::INF)) {
3320 if (script_list->is_anything_selected()) {
3321 pos = script_list->get_selected_items()[0];
3322 }
3323 } else {
3324 pos = script_list->get_item_at_position(p_point);
3325 }
3326 new_index = script_list->get_item_metadata(pos);
3327 }
3328 tab_container->move_child(node, new_index);
3329 tab_container->set_current_tab(new_index);
3330 _update_script_names();
3331 }
3332 }
3333
3334 if (String(d["type"]) == "nodes") {
3335 Array nodes = d["nodes"];
3336 if (nodes.is_empty()) {
3337 return;
3338 }
3339 Node *node = get_node(nodes[0]);
3340
3341 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(node);
3342 EditorHelp *eh = Object::cast_to<EditorHelp>(node);
3343 if (se || eh) {
3344 int new_index = 0;
3345 if (script_list->get_item_count() > 0) {
3346 int pos = 0;
3347 if (p_point == Vector2(Math::INF, Math::INF)) {
3348 if (script_list->is_anything_selected()) {
3349 pos = script_list->get_selected_items()[0];
3350 }
3351 } else {
3352 pos = script_list->get_item_at_position(p_point);
3353 }
3354 new_index = script_list->get_item_metadata(pos);
3355 }
3356 tab_container->move_child(node, new_index);
3357 tab_container->set_current_tab(new_index);
3358 _update_script_names();
3359 }
3360 }
3361
3362 if (String(d["type"]) == "files") {
3363 Vector<String> files = d["files"];
3364
3365 int new_index = 0;
3366 if (script_list->get_item_count() > 0) {
3367 int pos = 0;
3368 if (p_point == Vector2(Math::INF, Math::INF)) {
3369 if (script_list->is_anything_selected()) {
3370 pos = script_list->get_selected_items()[0];
3371 }
3372 } else {
3373 pos = script_list->get_item_at_position(p_point);
3374 }
3375 new_index = script_list->get_item_metadata(pos);
3376 }
3377 int num_tabs_before = tab_container->get_tab_count();
3378 for (int i = 0; i < files.size(); i++) {
3379 const String &file = files[i];
3380 if (file.is_empty() || !FileAccess::exists(file)) {
3381 continue;
3382 }
3383
3384 if (!ResourceLoader::exists(file, "Script") && !ResourceLoader::exists(file, "JSON") && !textfile_extensions.has(file.get_extension())) {
3385 continue;
3386 }
3387
3388 Ref<Resource> res = open_file(file);
3389 if (res.is_valid()) {
3390 const int num_tabs = tab_container->get_tab_count();
3391 if (num_tabs > num_tabs_before) {
3392 tab_container->move_child(tab_container->get_tab_control(tab_container->get_tab_count() - 1), new_index);
3393 num_tabs_before = num_tabs;
3394 } else if (num_tabs > 0) { /* Maybe script was already open */
3395 tab_container->move_child(tab_container->get_tab_control(tab_container->get_current_tab()), new_index);
3396 }
3397 }
3398 }
3399 if (tab_container->get_tab_count() > 0) {
3400 tab_container->set_current_tab(new_index);
3401 }
3402 _update_script_names();
3403 }
3404 }
3405
3406 void ScriptEditor::input(const Ref<InputEvent> &p_event) {
3407 // This is implemented in `input()` rather than `unhandled_input()` to allow
3408 // the shortcut to be used regardless of the click location.
3409 // This feature can be disabled to avoid interfering with other uses of the additional
3410 // mouse buttons, such as push-to-talk in a VoIP program.
3411 if (EDITOR_GET("interface/editor/mouse_extra_buttons_navigate_history")) {
3412 const Ref<InputEventMouseButton> mb = p_event;
3413
3414 // Navigate the script history using additional mouse buttons present on some mice.
3415 // This must be hardcoded as the editor shortcuts dialog doesn't allow assigning
3416 // more than one shortcut per action.
3417 if (mb.is_valid() && mb->is_pressed() && is_visible_in_tree()) {
3418 if (mb->get_button_index() == MouseButton::MB_XBUTTON1) {
3419 _history_back();
3420 }
3421
3422 if (mb->get_button_index() == MouseButton::MB_XBUTTON2) {
3423 _history_forward();
3424 }
3425 }
3426 }
3427 }
3428
3429 void ScriptEditor::shortcut_input(const Ref<InputEvent> &p_event) {
3430 ERR_FAIL_COND(p_event.is_null());
3431
3432 if (!is_visible_in_tree() || !p_event->is_pressed()) {
3433 return;
3434 }
3435 if (ED_IS_SHORTCUT("script_editor/next_script", p_event)) {
3436 if (script_list->get_item_count() > 1) {
3437 int next_tab = script_list->get_current() + 1;
3438 next_tab %= script_list->get_item_count();
3439 _go_to_tab(script_list->get_item_metadata(next_tab));
3440 _update_script_names();
3441 }
3442 accept_event();
3443 }
3444 if (ED_IS_SHORTCUT("script_editor/prev_script", p_event)) {
3445 if (script_list->get_item_count() > 1) {
3446 int next_tab = script_list->get_current() - 1;
3447 next_tab = next_tab >= 0 ? next_tab : script_list->get_item_count() - 1;
3448 _go_to_tab(script_list->get_item_metadata(next_tab));
3449 _update_script_names();
3450 }
3451 accept_event();
3452 }
3453 if (ED_IS_SHORTCUT("script_editor/window_move_up", p_event)) {
3454 _menu_option(FILE_MENU_MOVE_UP);
3455 accept_event();
3456 }
3457 if (ED_IS_SHORTCUT("script_editor/window_move_down", p_event)) {
3458 _menu_option(FILE_MENU_MOVE_DOWN);
3459 accept_event();
3460 }
3461
3462 if (p_event->is_echo()) {
3463 return;
3464 }
3465
3466 Callable custom_callback = EditorContextMenuPluginManager::get_singleton()->match_custom_shortcut(EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR, p_event);
3467 if (custom_callback.is_valid()) {
3468 Ref<Resource> resource;
3469 ScriptEditorBase *current = _get_current_editor();
3470 if (current) {
3471 resource = current->get_edited_resource();
3472 }
3473 EditorContextMenuPluginManager::get_singleton()->invoke_callback(custom_callback, resource);
3474 accept_event();
3475 }
3476 }
3477
3478 void ScriptEditor::_script_list_clicked(int p_item, Vector2 p_local_mouse_pos, MouseButton p_mouse_button_index) {
3479 if (p_mouse_button_index == MouseButton::MIDDLE) {
3480 script_list->select(p_item);
3481 _script_selected(p_item);
3482 _menu_option(FILE_MENU_CLOSE);
3483 }
3484
3485 if (p_mouse_button_index == MouseButton::RIGHT) {
3486 _make_script_list_context_menu();
3487 }
3488 }
3489
3490 void ScriptEditor::_make_script_list_context_menu() {
3491 context_menu->clear();
3492
3493 int selected = tab_container->get_current_tab();
3494 if (selected < 0 || selected >= tab_container->get_tab_count()) {
3495 return;
3496 }
3497
3498 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(selected));
3499 if (se) {
3500 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/save"), FILE_MENU_SAVE);
3501 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/save_as"), FILE_MENU_SAVE_AS);
3502 }
3503 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/close_file"), FILE_MENU_CLOSE);
3504 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/close_other_tabs"), FILE_MENU_CLOSE_OTHER_TABS);
3505 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/close_tabs_below"), FILE_MENU_CLOSE_TABS_BELOW);
3506 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/close_all"), FILE_MENU_CLOSE_ALL);
3507 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/close_docs"), FILE_MENU_CLOSE_DOCS);
3508 context_menu->add_separator();
3509 if (se) {
3510 Ref<Script> scr = se->get_edited_resource();
3511 if (scr.is_valid() && scr->is_tool()) {
3512 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/reload_script_soft"), FILE_MENU_SOFT_RELOAD_TOOL);
3513 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/run_file"), FILE_MENU_RUN);
3514 context_menu->add_separator();
3515 }
3516 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/copy_path"), FILE_MENU_COPY_PATH);
3517 context_menu->set_item_disabled(-1, se->get_edited_resource()->get_path().is_empty());
3518 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/copy_uid"), FILE_MENU_COPY_UID);
3519 context_menu->set_item_disabled(-1, ResourceLoader::get_resource_uid(se->get_edited_resource()->get_path()) == ResourceUID::INVALID_ID);
3520 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/show_in_file_system"), FILE_MENU_SHOW_IN_FILE_SYSTEM);
3521 context_menu->add_separator();
3522 }
3523
3524 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/window_move_up"), FILE_MENU_MOVE_UP);
3525 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/window_move_down"), FILE_MENU_MOVE_DOWN);
3526 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/window_sort"), FILE_MENU_SORT);
3527 context_menu->add_shortcut(ED_GET_SHORTCUT("script_editor/toggle_files_panel"), FILE_MENU_TOGGLE_FILES_PANEL);
3528
3529 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_CLOSE_ALL), tab_container->get_tab_count() <= 0);
3530 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_CLOSE_OTHER_TABS), tab_container->get_tab_count() <= 1);
3531 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_CLOSE_DOCS), !_has_docs_tab());
3532 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_CLOSE_TABS_BELOW), tab_container->get_current_tab() >= tab_container->get_tab_count() - 1);
3533 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_MOVE_UP), tab_container->get_current_tab() <= 0);
3534 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_MOVE_DOWN), tab_container->get_current_tab() >= tab_container->get_tab_count() - 1);
3535 context_menu->set_item_disabled(context_menu->get_item_index(FILE_MENU_SORT), tab_container->get_tab_count() <= 1);
3536
3537 // Context menu plugin.
3538 Vector<String> selected_paths;
3539 if (se) {
3540 Ref<Resource> scr = se->get_edited_resource();
3541 if (scr.is_valid()) {
3542 String path = scr->get_path();
3543 selected_paths.push_back(path);
3544 }
3545 }
3546 EditorContextMenuPluginManager::get_singleton()->add_options_from_plugins(context_menu, EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR, selected_paths);
3547
3548 context_menu->set_position(get_screen_position() + get_local_mouse_position());
3549 context_menu->reset_size();
3550 context_menu->popup();
3551 }
3552
3553 void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) {
3554 if (!bool(EDITOR_GET("text_editor/behavior/files/restore_scripts_on_load"))) {
3555 return;
3556 }
3557
3558 if (!p_layout->has_section_key("ScriptEditor", "open_scripts") && !p_layout->has_section_key("ScriptEditor", "open_help")) {
3559 return;
3560 }
3561
3562 Array scripts = p_layout->get_value("ScriptEditor", "open_scripts");
3563 Array helps;
3564 if (p_layout->has_section_key("ScriptEditor", "open_help")) {
3565 helps = p_layout->get_value("ScriptEditor", "open_help");
3566 }
3567
3568 restoring_layout = true;
3569
3570 HashSet<String> loaded_scripts;
3571 List<String> extensions;
3572 ResourceLoader::get_recognized_extensions_for_type("Script", &extensions);
3573 ResourceLoader::get_recognized_extensions_for_type("JSON", &extensions);
3574
3575 for (const Variant &v : scripts) {
3576 String path = v;
3577
3578 Dictionary script_info = v;
3579 if (!script_info.is_empty()) {
3580 path = script_info["path"];
3581 }
3582
3583 if (!_script_exists(path)) {
3584 if (script_editor_cache->has_section(path)) {
3585 script_editor_cache->erase_section(path);
3586 }
3587 continue;
3588 } else if (!path.is_resource_file() && !EditorNode::get_singleton()->is_scene_open(path.get_slice("::", 0))) {
3589 continue;
3590 }
3591 loaded_scripts.insert(path);
3592
3593 bool is_script = false;
3594 if (path.is_resource_file()) {
3595 is_script = extensions.find(path.get_extension());
3596 } else {
3597 Ref<Script> scr = ResourceCache::get_ref(path);
3598 if (scr.is_valid()) {
3599 is_script = true;
3600 } else {
3601 continue;
3602 }
3603 }
3604
3605 if (is_script) {
3606 Ref<Resource> scr = ResourceLoader::load(path);
3607 if (scr.is_null()) {
3608 continue;
3609 }
3610 if (!edit(scr, false)) {
3611 continue;
3612 }
3613 } else {
3614 Error error;
3615 Ref<TextFile> text_file = _load_text_file(path, &error);
3616 if (error != OK || text_file.is_null()) {
3617 continue;
3618 }
3619 if (!edit(text_file, false)) {
3620 continue;
3621 }
3622 }
3623
3624 if (!script_info.is_empty()) {
3625 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(tab_container->get_tab_count() - 1));
3626 if (se) {
3627 se->set_edit_state(script_info["state"]);
3628 }
3629 }
3630 }
3631
3632 for (int i = 0; i < helps.size(); i++) {
3633 String path = helps[i];
3634 if (path.is_empty()) { // invalid, skip
3635 continue;
3636 }
3637 _help_class_open(path);
3638 }
3639
3640 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3641 tab_container->get_tab_control(i)->set_meta("__editor_pass", Variant());
3642 }
3643
3644 if (p_layout->has_section_key("ScriptEditor", "script_split_offset")) {
3645 script_split->set_split_offset(p_layout->get_value("ScriptEditor", "script_split_offset"));
3646 }
3647
3648 if (p_layout->has_section_key("ScriptEditor", "list_split_offset")) {
3649 list_split->set_split_offset(p_layout->get_value("ScriptEditor", "list_split_offset"));
3650 }
3651
3652 // Remove any deleted editors that have been removed between launches.
3653 // and if a Script, register breakpoints with the debugger.
3654 Vector<String> cached_editors = script_editor_cache->get_sections();
3655 for (const String &E : cached_editors) {
3656 if (loaded_scripts.has(E)) {
3657 continue;
3658 }
3659
3660 if (!_script_exists(E)) {
3661 script_editor_cache->erase_section(E);
3662 continue;
3663 }
3664
3665 Array breakpoints = _get_cached_breakpoints_for_script(E);
3666 for (int breakpoint : breakpoints) {
3667 EditorDebuggerNode::get_singleton()->set_breakpoint(E, (int)breakpoint + 1, true);
3668 }
3669 }
3670
3671 _set_script_zoom_factor(p_layout->get_value("ScriptEditor", "zoom_factor", 1.0f));
3672
3673 restoring_layout = false;
3674
3675 _update_script_names();
3676
3677 if (p_layout->has_section_key("ScriptEditor", "selected_script")) {
3678 String selected_script = p_layout->get_value("ScriptEditor", "selected_script");
3679 // If the selected script is not in the list of open scripts, select nothing.
3680 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3681 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3682 if (se && se->get_edited_resource()->get_path() == selected_script) {
3683 _go_to_tab(i);
3684 break;
3685 }
3686 }
3687 }
3688 }
3689
3690 void ScriptEditor::get_window_layout(Ref<ConfigFile> p_layout) {
3691 Array scripts;
3692 Array helps;
3693 String selected_script;
3694 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3695 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3696 if (se) {
3697 const String path = se->get_edited_resource()->get_path();
3698 if (path.is_empty()) {
3699 continue;
3700 }
3701
3702 if (tab_container->get_current_tab_control() == tab_container->get_tab_control(i)) {
3703 selected_script = path;
3704 }
3705
3706 _save_editor_state(se);
3707 scripts.push_back(path);
3708 }
3709
3710 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
3711
3712 if (eh) {
3713 helps.push_back(eh->get_class());
3714 }
3715 }
3716
3717 p_layout->set_value("ScriptEditor", "open_scripts", scripts);
3718 p_layout->set_value("ScriptEditor", "selected_script", selected_script);
3719 p_layout->set_value("ScriptEditor", "open_help", helps);
3720 p_layout->set_value("ScriptEditor", "script_split_offset", script_split->get_split_offset());
3721 p_layout->set_value("ScriptEditor", "list_split_offset", list_split->get_split_offset());
3722 p_layout->set_value("ScriptEditor", "zoom_factor", zoom_factor);
3723
3724 // Save the cache.
3725 script_editor_cache->save(EditorPaths::get_singleton()->get_project_settings_dir().path_join("script_editor_cache.cfg"));
3726 }
3727
3728 void ScriptEditor::_help_class_open(const String &p_class) {
3729 if (p_class.is_empty()) {
3730 return;
3731 }
3732
3733 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3734 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
3735
3736 if (eh && eh->get_class() == p_class) {
3737 _go_to_tab(i);
3738 _update_script_names();
3739 return;
3740 }
3741 }
3742
3743 EditorHelp *eh = memnew(EditorHelp);
3744
3745 eh->set_name(p_class);
3746 tab_container->add_child(eh);
3747 _go_to_tab(tab_container->get_tab_count() - 1);
3748 eh->go_to_class(p_class);
3749 eh->connect("go_to_help", callable_mp(this, &ScriptEditor::_help_class_goto));
3750 eh->connect("request_save_history", callable_mp(this, &ScriptEditor::_save_history));
3751 _add_recent_script(p_class);
3752 _sort_list_on_update = true;
3753 _update_script_names();
3754 _save_layout();
3755 }
3756
3757 void ScriptEditor::_help_class_goto(const String &p_desc) {
3758 String cname = p_desc.get_slicec(':', 1);
3759
3760 if (_help_tab_goto(cname, p_desc)) {
3761 return;
3762 }
3763
3764 EditorHelp *eh = memnew(EditorHelp);
3765
3766 eh->set_name(cname);
3767 tab_container->add_child(eh);
3768 _go_to_tab(tab_container->get_tab_count() - 1);
3769 eh->go_to_help(p_desc);
3770 eh->connect("go_to_help", callable_mp(this, &ScriptEditor::_help_class_goto));
3771 _add_recent_script(eh->get_class());
3772 _sort_list_on_update = true;
3773 _update_script_names();
3774 _save_layout();
3775 }
3776
3777 bool ScriptEditor::_help_tab_goto(const String &p_name, const String &p_desc) {
3778 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3779 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
3780
3781 if (eh && eh->get_class() == p_name) {
3782 _go_to_tab(i);
3783 eh->go_to_help(p_desc);
3784 _update_script_names();
3785 return true;
3786 }
3787 }
3788 return false;
3789 }
3790
3791 void ScriptEditor::update_doc(const String &p_name) {
3792 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3793 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i));
3794 if (eh && eh->get_class() == p_name) {
3795 eh->update_doc();
3796 return;
3797 }
3798 }
3799 }
3800
3801 void ScriptEditor::clear_docs_from_script(const Ref<Script> &p_script) {
3802 ERR_FAIL_COND(p_script.is_null());
3803
3804 for (const DocData::ClassDoc &cd : p_script->get_documentation()) {
3805 if (EditorHelp::get_doc_data()->has_doc(cd.name)) {
3806 EditorHelp::get_doc_data()->remove_doc(cd.name);
3807 }
3808 }
3809 }
3810
3811 void ScriptEditor::update_docs_from_script(const Ref<Script> &p_script) {
3812 ERR_FAIL_COND(p_script.is_null());
3813
3814 for (const DocData::ClassDoc &cd : p_script->get_documentation()) {
3815 EditorHelp::get_doc_data()->add_doc(cd);
3816 update_doc(cd.name);
3817 }
3818 }
3819
3820 void ScriptEditor::_update_selected_editor_menu() {
3821 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3822 bool current = tab_container->get_current_tab() == i;
3823
3824 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3825 if (se && se->get_edit_menu()) {
3826 if (current) {
3827 se->get_edit_menu()->show();
3828 } else {
3829 se->get_edit_menu()->hide();
3830 }
3831 }
3832 }
3833
3834 EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_current_tab_control());
3835 script_search_menu->get_popup()->clear();
3836 if (eh) {
3837 script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find", TTRC("Find..."), KeyModifierMask::CMD_OR_CTRL | Key::F), HELP_SEARCH_FIND);
3838 script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_next", TTRC("Find Next"), Key::F3), HELP_SEARCH_FIND_NEXT);
3839 script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_previous", TTRC("Find Previous"), KeyModifierMask::SHIFT | Key::F3), HELP_SEARCH_FIND_PREVIOUS);
3840 script_search_menu->get_popup()->add_separator();
3841 script_search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("editor/find_in_files"), SEARCH_IN_FILES);
3842 script_search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_editor/replace_in_files"), REPLACE_IN_FILES);
3843 script_search_menu->show();
3844 } else {
3845 if (tab_container->get_tab_count() == 0) {
3846 script_search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("editor/find_in_files"), SEARCH_IN_FILES);
3847 script_search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_editor/replace_in_files"), REPLACE_IN_FILES);
3848 script_search_menu->show();
3849 } else {
3850 script_search_menu->hide();
3851 }
3852 }
3853 }
3854
3855 void ScriptEditor::_unlock_history() {
3856 lock_history = false;
3857 }
3858
3859 void ScriptEditor::_update_history_pos(int p_new_pos) {
3860 Node *n = tab_container->get_current_tab_control();
3861
3862 if (Object::cast_to<ScriptEditorBase>(n)) {
3863 history.write[history_pos].state = Object::cast_to<ScriptEditorBase>(n)->get_navigation_state();
3864 }
3865 if (Object::cast_to<EditorHelp>(n)) {
3866 history.write[history_pos].state = Object::cast_to<EditorHelp>(n)->get_scroll();
3867 }
3868
3869 history_pos = p_new_pos;
3870 tab_container->set_current_tab(tab_container->get_tab_idx_from_control(history[history_pos].control));
3871
3872 n = history[history_pos].control;
3873
3874 ScriptEditorBase *seb = Object::cast_to<ScriptEditorBase>(n);
3875 if (seb) {
3876 lock_history = true;
3877 seb->set_edit_state(history[history_pos].state);
3878 // `set_edit_state()` can modify the caret position which might trigger a
3879 // request to save the history. Since `TextEdit::caret_changed` is emitted
3880 // deferred, we need to defer unlocking of the history as well.
3881 callable_mp(this, &ScriptEditor::_unlock_history).call_deferred();
3882 seb->ensure_focus();
3883
3884 Ref<Script> scr = seb->get_edited_resource();
3885 if (scr.is_valid()) {
3886 notify_script_changed(scr);
3887 }
3888
3889 seb->validate();
3890 }
3891
3892 EditorHelp *eh = Object::cast_to<EditorHelp>(n);
3893 if (eh) {
3894 eh->set_scroll(history[history_pos].state);
3895 eh->set_focused();
3896 }
3897
3898 n->set_meta("__editor_pass", ++edit_pass);
3899 _update_script_names();
3900 _update_history_arrows();
3901 _update_selected_editor_menu();
3902 }
3903
3904 void ScriptEditor::_history_forward() {
3905 if (history_pos < history.size() - 1) {
3906 _update_history_pos(history_pos + 1);
3907 }
3908 }
3909
3910 void ScriptEditor::_history_back() {
3911 if (history_pos > 0) {
3912 _update_history_pos(history_pos - 1);
3913 }
3914 }
3915
3916 Vector<Ref<Script>> ScriptEditor::get_open_scripts() const {
3917 Vector<Ref<Script>> out_scripts = Vector<Ref<Script>>();
3918
3919 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3920 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3921 if (!se) {
3922 continue;
3923 }
3924
3925 Ref<Script> scr = se->get_edited_resource();
3926 if (scr.is_valid()) {
3927 out_scripts.push_back(scr);
3928 }
3929 }
3930
3931 return out_scripts;
3932 }
3933
3934 TypedArray<ScriptEditorBase> ScriptEditor::_get_open_script_editors() const {
3935 TypedArray<ScriptEditorBase> script_editors;
3936 for (int i = 0; i < tab_container->get_tab_count(); i++) {
3937 ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_tab_control(i));
3938 if (!se) {
3939 continue;
3940 }
3941 script_editors.push_back(se);
3942 }
3943 return script_editors;
3944 }
3945
3946 void ScriptEditor::set_scene_root_script(Ref<Script> p_script) {
3947 // Don't open dominant script if using an external editor.
3948 bool use_external_editor =
3949 external_editor_active ||
3950 (p_script.is_valid() && p_script->get_language()->overrides_external_editor());
3951 use_external_editor = use_external_editor && !(p_script.is_valid() && p_script->is_built_in()); // Ignore external editor for built-in scripts.
3952 const bool open_dominant = EDITOR_GET("text_editor/behavior/files/open_dominant_script_on_scene_change");
3953
3954 if (open_dominant && !use_external_editor && p_script.is_valid()) {
3955 edit(p_script);
3956 }
3957 }
3958
3959 bool ScriptEditor::script_goto_method(Ref<Script> p_script, const String &p_method) {
3960 int line = p_script->get_member_line(p_method);
3961
3962 if (line == -1) {
3963 return false;
3964 }
3965
3966 return edit(p_script, line, 0);
3967 }
3968
3969 void ScriptEditor::set_live_auto_reload_running_scripts(bool p_enabled) {
3970 auto_reload_running_scripts = p_enabled;
3971 }
3972
3973 void ScriptEditor::_help_search(const String &p_text) {
3974 help_search_dialog->popup_dialog(p_text);
3975 }
3976
3977 void ScriptEditor::_open_script_request(const String &p_path) {
3978 Ref<Script> scr = ResourceLoader::load(p_path);
3979 if (scr.is_valid()) {
3980 script_editor->edit(scr, false);
3981 return;
3982 }
3983
3984 Ref<JSON> json = ResourceLoader::load(p_path);
3985 if (json.is_valid()) {
3986 script_editor->edit(json, false);
3987 return;
3988 }
3989
3990 Error err;
3991 Ref<TextFile> text_file = script_editor->_load_text_file(p_path, &err);
3992 if (text_file.is_valid()) {
3993 script_editor->edit(text_file, false);
3994 return;
3995 }
3996 }
3997
3998 void ScriptEditor::register_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter) {
3999 ERR_FAIL_COND(p_syntax_highlighter.is_null());
4000
4001 if (!syntax_highlighters.has(p_syntax_highlighter)) {
4002 syntax_highlighters.push_back(p_syntax_highlighter);
4003 }
4004 }
4005
4006 void ScriptEditor::unregister_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter) {
4007 ERR_FAIL_COND(p_syntax_highlighter.is_null());
4008
4009 syntax_highlighters.erase(p_syntax_highlighter);
4010 }
4011
4012 int ScriptEditor::script_editor_func_count = 0;
4013 CreateScriptEditorFunc ScriptEditor::script_editor_funcs[ScriptEditor::SCRIPT_EDITOR_FUNC_MAX];
4014
4015 void ScriptEditor::register_create_script_editor_function(CreateScriptEditorFunc p_func) {
4016 ERR_FAIL_COND(script_editor_func_count == SCRIPT_EDITOR_FUNC_MAX);
4017 script_editor_funcs[script_editor_func_count++] = p_func;
4018 }
4019
4020 void ScriptEditor::_script_changed() {
4021 SignalsDock::get_singleton()->update_lists();
4022 }
4023
4024 void ScriptEditor::_on_replace_in_files_requested(const String &text) {
4025 find_in_files_dialog->set_find_in_files_mode(FindInFilesDialog::REPLACE_MODE);
4026 find_in_files_dialog->set_search_text(text);
4027 find_in_files_dialog->set_replace_text("");
4028 find_in_files_dialog->popup_centered();
4029 }
4030
4031 void ScriptEditor::_on_find_in_files_result_selected(const String &fpath, int line_number, int begin, int end) {
4032 if (ResourceLoader::exists(fpath)) {
4033 Ref<Resource> res = ResourceLoader::load(fpath);
4034
4035 if (fpath.get_extension() == "gdshader") {
4036 ShaderEditorPlugin *shader_editor = Object::cast_to<ShaderEditorPlugin>(EditorNode::get_editor_data().get_editor_by_name("Shader"));
4037 shader_editor->edit(res.ptr());
4038 shader_editor->make_visible(true);
4039 TextShaderEditor *text_shader_editor = Object::cast_to<TextShaderEditor>(shader_editor->get_shader_editor(res));
4040 if (text_shader_editor) {
4041 text_shader_editor->goto_line_selection(line_number - 1, begin, end);
4042 }
4043 return;
4044 } else if (fpath.get_extension() == "tscn") {
4045 const PackedStringArray lines = FileAccess::get_file_as_string(fpath).split("\n");
4046 if (line_number > lines.size()) {
4047 return;
4048 }
4049
4050 const char *scr_header = "[sub_resource type=\"GDScript\" id=\"";
4051 const char *source_header = "script/source = \"";
4052 String script_id;
4053
4054 // Search the scene backwards from the found line.
4055 int scan_line = line_number - 1;
4056 while (scan_line >= 0) {
4057 const String &line = lines[scan_line];
4058 if (line.begins_with(source_header)) {
4059 // Adjust line relative to the script beginning.
4060 line_number -= scan_line + 1;
4061 } else if (line.begins_with(scr_header)) {
4062 script_id = line.trim_prefix(scr_header).get_slicec('"', 0);
4063 break;
4064 }
4065 scan_line--;
4066 }
4067
4068 EditorNode::get_singleton()->load_scene(fpath);
4069 if (!script_id.is_empty()) {
4070 Ref<Script> scr = ResourceLoader::load(fpath + "::" + script_id, "Script");
4071 if (scr.is_valid()) {
4072 edit(scr);
4073 ScriptTextEditor *ste = Object::cast_to<ScriptTextEditor>(_get_current_editor());
4074
4075 if (ste) {
4076 callable_mp(EditorInterface::get_singleton(), &EditorInterface::set_main_screen_editor).call_deferred("Script");
4077 if (line_number == 0) {
4078 const int source_len = strlen(source_header);
4079 ste->goto_line_selection(line_number, begin - source_len, end - source_len);
4080 } else {
4081 ste->goto_line_selection(line_number, begin, end);
4082 }
4083 }
4084 }
4085 }
4086
4087 return;
4088 } else {
4089 Ref<Script> scr = res;
4090 Ref<JSON> json = res;
4091 if (scr.is_valid() || json.is_valid()) {
4092 edit(scr);
4093
4094 ScriptTextEditor *ste = Object::cast_to<ScriptTextEditor>(_get_current_editor());
4095 if (ste) {
4096 EditorInterface::get_singleton()->set_main_screen_editor("Script");
4097 ste->goto_line_selection(line_number - 1, begin, end);
4098 }
4099 return;
4100 }
4101 }
4102 }
4103
4104 // If the file is not a valid resource/script, load it as a text file.
4105 Error err;
4106 Ref<TextFile> text_file = _load_text_file(fpath, &err);
4107 if (text_file.is_valid()) {
4108 edit(text_file);
4109
4110 TextEditor *te = Object::cast_to<TextEditor>(_get_current_editor());
4111 if (te) {
4112 te->goto_line_selection(line_number - 1, begin, end);
4113 }
4114 }
4115 }
4116
4117 void ScriptEditor::_start_find_in_files(bool with_replace) {
4118 FindInFilesPanel *panel = find_in_files->get_panel_for_results(with_replace ? TTR("Replace:") + " " + find_in_files_dialog->get_search_text() : TTR("Find:") + " " + find_in_files_dialog->get_search_text());
4119 FindInFiles *f = panel->get_finder();
4120
4121 f->set_search_text(find_in_files_dialog->get_search_text());
4122 f->set_match_case(find_in_files_dialog->is_match_case());
4123 f->set_whole_words(find_in_files_dialog->is_whole_words());
4124 f->set_folder(find_in_files_dialog->get_folder());
4125 f->set_filter(find_in_files_dialog->get_filter());
4126 f->set_includes(find_in_files_dialog->get_includes());
4127 f->set_excludes(find_in_files_dialog->get_excludes());
4128
4129 panel->set_with_replace(with_replace);
4130 panel->set_replace_text(find_in_files_dialog->get_replace_text());
4131 panel->start_search();
4132
4133 find_in_files->make_visible();
4134 }
4135
4136 void ScriptEditor::_on_find_in_files_modified_files(const PackedStringArray &paths) {
4137 _test_script_times_on_disk();
4138 _update_modified_scripts_for_external_editor();
4139 }
4140
4141 void ScriptEditor::_set_script_zoom_factor(float p_zoom_factor) {
4142 if (zoom_factor == p_zoom_factor) {
4143 return;
4144 }
4145
4146 zoom_factor = p_zoom_factor;
4147 }
4148
4149 void ScriptEditor::_update_code_editor_zoom_factor(CodeTextEditor *p_code_text_editor) {
4150 if (p_code_text_editor && p_code_text_editor->is_visible_in_tree() && zoom_factor != p_code_text_editor->get_zoom_factor()) {
4151 p_code_text_editor->set_zoom_factor(zoom_factor);
4152 }
4153 }
4154
4155 void ScriptEditor::_window_changed(bool p_visible) {
4156 make_floating->set_visible(!p_visible);
4157 is_floating = p_visible;
4158 }
4159
4160 void ScriptEditor::_filter_scripts_text_changed(const String &p_newtext) {
4161 _update_script_names();
4162 }
4163
4164 void ScriptEditor::_filter_methods_text_changed(const String &p_newtext) {
4165 _update_members_overview();
4166 }
4167
4168 void ScriptEditor::_bind_methods() {
4169 ClassDB::bind_method("_help_tab_goto", &ScriptEditor::_help_tab_goto);
4170 ClassDB::bind_method("get_current_editor", &ScriptEditor::_get_current_editor);
4171 ClassDB::bind_method("get_open_script_editors", &ScriptEditor::_get_open_script_editors);
4172 ClassDB::bind_method("get_breakpoints", &ScriptEditor::_get_breakpoints);
4173
4174 ClassDB::bind_method(D_METHOD("register_syntax_highlighter", "syntax_highlighter"), &ScriptEditor::register_syntax_highlighter);
4175 ClassDB::bind_method(D_METHOD("unregister_syntax_highlighter", "syntax_highlighter"), &ScriptEditor::unregister_syntax_highlighter);
4176
4177 ClassDB::bind_method(D_METHOD("goto_line", "line_number"), &ScriptEditor::_goto_script_line2);
4178 ClassDB::bind_method(D_METHOD("get_current_script"), &ScriptEditor::_get_current_script);
4179 ClassDB::bind_method(D_METHOD("get_open_scripts"), &ScriptEditor::_get_open_scripts);
4180 ClassDB::bind_method(D_METHOD("open_script_create_dialog", "base_name", "base_path"), &ScriptEditor::open_script_create_dialog);
4181
4182 ClassDB::bind_method(D_METHOD("goto_help", "topic"), &ScriptEditor::goto_help);
4183 ClassDB::bind_method(D_METHOD("update_docs_from_script", "script"), &ScriptEditor::update_docs_from_script);
4184 ClassDB::bind_method(D_METHOD("clear_docs_from_script", "script"), &ScriptEditor::clear_docs_from_script);
4185
4186 ADD_SIGNAL(MethodInfo("editor_script_changed", PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script")));
4187 ADD_SIGNAL(MethodInfo("script_close", PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script")));
4188 }
4189
4190 ScriptEditor::ScriptEditor(WindowWrapper *p_wrapper) {
4191 window_wrapper = p_wrapper;
4192
4193 script_editor_cache.instantiate();
4194 script_editor_cache->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("script_editor_cache.cfg"));
4195
4196 restoring_layout = false;
4197 waiting_update_names = false;
4198 pending_auto_reload = false;
4199 auto_reload_running_scripts = true;
4200 external_editor_active = false;
4201 members_overview_enabled = EDITOR_GET("text_editor/script_list/show_members_overview");
4202 help_overview_enabled = EDITOR_GET("text_editor/help/show_help_index");
4203
4204 VBoxContainer *main_container = memnew(VBoxContainer);
4205 add_child(main_container);
4206
4207 menu_hb = memnew(HBoxContainer);
4208 main_container->add_child(menu_hb);
4209
4210 script_split = memnew(HSplitContainer);
4211 main_container->add_child(script_split);
4212 script_split->set_v_size_flags(SIZE_EXPAND_FILL);
4213
4214 #ifdef ANDROID_ENABLED
4215 virtual_keyboard_spacer = memnew(Control);
4216 virtual_keyboard_spacer->set_h_size_flags(SIZE_EXPAND_FILL);
4217 main_container->add_child(virtual_keyboard_spacer);
4218 #endif
4219
4220 list_split = memnew(VSplitContainer);
4221 script_split->add_child(list_split);
4222 list_split->set_v_size_flags(SIZE_EXPAND_FILL);
4223
4224 scripts_vbox = memnew(VBoxContainer);
4225 scripts_vbox->set_v_size_flags(SIZE_EXPAND_FILL);
4226 list_split->add_child(scripts_vbox);
4227
4228 filter_scripts = memnew(LineEdit);
4229 filter_scripts->set_placeholder(TTRC("Filter Scripts"));
4230 filter_scripts->set_accessibility_name(TTRC("Filter Scripts"));
4231 filter_scripts->set_clear_button_enabled(true);
4232 filter_scripts->connect(SceneStringName(text_changed), callable_mp(this, &ScriptEditor::_filter_scripts_text_changed));
4233 scripts_vbox->add_child(filter_scripts);
4234
4235 _sort_list_on_update = true;
4236 script_list = memnew(ItemList);
4237 script_list->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4238 script_list->set_custom_minimum_size(Size2(100, 60) * EDSCALE); //need to give a bit of limit to avoid it from disappearing
4239 script_list->set_v_size_flags(SIZE_EXPAND_FILL);
4240 script_list->set_theme_type_variation("ItemListSecondary");
4241 script_split->set_split_offset(200 * EDSCALE);
4242 script_list->set_allow_rmb_select(true);
4243 scripts_vbox->add_child(script_list);
4244 script_list->connect("item_clicked", callable_mp(this, &ScriptEditor::_script_list_clicked), CONNECT_DEFERRED);
4245 SET_DRAG_FORWARDING_GCD(script_list, ScriptEditor);
4246
4247 context_menu = memnew(PopupMenu);
4248 add_child(context_menu);
4249 context_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptEditor::_menu_option));
4250
4251 overview_vbox = memnew(VBoxContainer);
4252 overview_vbox->set_custom_minimum_size(Size2(0, 90));
4253 overview_vbox->set_v_size_flags(SIZE_EXPAND_FILL);
4254
4255 list_split->add_child(overview_vbox);
4256 list_split->set_visible(EditorSettings::get_singleton()->get_project_metadata("files_panel", "show_files_panel", true));
4257 buttons_hbox = memnew(HBoxContainer);
4258 overview_vbox->add_child(buttons_hbox);
4259
4260 filter_methods = memnew(LineEdit);
4261 filter_methods->set_placeholder(TTRC("Filter Methods"));
4262 filter_methods->set_accessibility_name(TTRC("Filter Methods"));
4263 filter_methods->set_clear_button_enabled(true);
4264 filter_methods->set_h_size_flags(SIZE_EXPAND_FILL);
4265 filter_methods->connect(SceneStringName(text_changed), callable_mp(this, &ScriptEditor::_filter_methods_text_changed));
4266 buttons_hbox->add_child(filter_methods);
4267
4268 members_overview_alphabeta_sort_button = memnew(Button);
4269 members_overview_alphabeta_sort_button->set_theme_type_variation(SceneStringName(FlatButton));
4270 members_overview_alphabeta_sort_button->set_tooltip_text(TTRC("Toggle alphabetical sorting of the method list."));
4271 members_overview_alphabeta_sort_button->set_toggle_mode(true);
4272 members_overview_alphabeta_sort_button->set_pressed(EDITOR_GET("text_editor/script_list/sort_members_outline_alphabetically"));
4273 members_overview_alphabeta_sort_button->connect(SceneStringName(toggled), callable_mp(this, &ScriptEditor::_toggle_members_overview_alpha_sort));
4274 buttons_hbox->add_child(members_overview_alphabeta_sort_button);
4275
4276 members_overview = memnew(ItemList);
4277 members_overview->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4278 members_overview->set_theme_type_variation("ItemListSecondary");
4279 overview_vbox->add_child(members_overview);
4280
4281 members_overview->set_allow_reselect(true);
4282 members_overview->set_custom_minimum_size(Size2(0, 60) * EDSCALE); //need to give a bit of limit to avoid it from disappearing
4283 members_overview->set_v_size_flags(SIZE_EXPAND_FILL);
4284 members_overview->set_allow_rmb_select(true);
4285
4286 help_overview = memnew(ItemList);
4287 help_overview->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4288 help_overview->set_theme_type_variation("ItemListSecondary");
4289 overview_vbox->add_child(help_overview);
4290 help_overview->set_allow_reselect(true);
4291 help_overview->set_custom_minimum_size(Size2(0, 60) * EDSCALE); //need to give a bit of limit to avoid it from disappearing
4292 help_overview->set_v_size_flags(SIZE_EXPAND_FILL);
4293
4294 VBoxContainer *code_editor_container = memnew(VBoxContainer);
4295 script_split->add_child(code_editor_container);
4296
4297 tab_container = memnew(TabContainer);
4298 tab_container->set_tabs_visible(false);
4299 tab_container->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
4300 code_editor_container->add_child(tab_container);
4301 tab_container->set_h_size_flags(SIZE_EXPAND_FILL);
4302 tab_container->set_v_size_flags(SIZE_EXPAND_FILL);
4303
4304 find_replace_bar = memnew(FindReplaceBar);
4305 code_editor_container->add_child(find_replace_bar);
4306 find_replace_bar->hide();
4307
4308 ED_SHORTCUT("script_editor/window_sort", TTRC("Sort"));
4309 ED_SHORTCUT("script_editor/window_move_up", TTRC("Move Up"), KeyModifierMask::SHIFT | KeyModifierMask::ALT | Key::UP);
4310 ED_SHORTCUT("script_editor/window_move_down", TTRC("Move Down"), KeyModifierMask::SHIFT | KeyModifierMask::ALT | Key::DOWN);
4311 // FIXME: These should be `Key::GREATER` and `Key::LESS` but those don't work.
4312 ED_SHORTCUT("script_editor/next_script", TTRC("Next Script"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::PERIOD);
4313 ED_SHORTCUT("script_editor/prev_script", TTRC("Previous Script"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::COMMA);
4314 set_process_input(true);
4315 set_process_shortcut_input(true);
4316
4317 file_menu = memnew(MenuButton);
4318 file_menu->set_flat(false);
4319 file_menu->set_theme_type_variation("FlatMenuButton");
4320 file_menu->set_text(TTRC("File"));
4321 file_menu->set_switch_on_hover(true);
4322 file_menu->set_shortcut_context(this);
4323 menu_hb->add_child(file_menu);
4324
4325 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/new", TTRC("New Script..."), KeyModifierMask::CMD_OR_CTRL | Key::N), FILE_MENU_NEW);
4326 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/new_textfile", TTRC("New Text File..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::N), FILE_MENU_NEW_TEXTFILE);
4327 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/open", TTRC("Open...")), FILE_MENU_OPEN);
4328 file_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_editor/reopen_closed_script"), FILE_MENU_REOPEN_CLOSED);
4329
4330 recent_scripts = memnew(PopupMenu);
4331 recent_scripts->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4332 file_menu->get_popup()->add_submenu_node_item(TTRC("Open Recent"), recent_scripts, FILE_MENU_OPEN_RECENT);
4333 recent_scripts->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptEditor::_open_recent_script));
4334
4335 _update_recent_scripts();
4336
4337 file_menu->get_popup()->add_separator();
4338 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save", TTRC("Save"), KeyModifierMask::ALT | KeyModifierMask::CMD_OR_CTRL | Key::S), FILE_MENU_SAVE);
4339 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_as", TTRC("Save As...")), FILE_MENU_SAVE_AS);
4340 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_all", TTRC("Save All"), KeyModifierMask::SHIFT | KeyModifierMask::ALT | Key::S), FILE_MENU_SAVE_ALL);
4341 ED_SHORTCUT_OVERRIDE("script_editor/save_all", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::S);
4342 file_menu->get_popup()->add_separator();
4343 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/reload_script_soft", TTRC("Soft Reload Tool Script"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::R), FILE_MENU_SOFT_RELOAD_TOOL);
4344 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/copy_path", TTRC("Copy Script Path")), FILE_MENU_COPY_PATH);
4345 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/copy_uid", TTRC("Copy Script UID")), FILE_MENU_COPY_UID);
4346 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/show_in_file_system", TTRC("Show in FileSystem")), FILE_MENU_SHOW_IN_FILE_SYSTEM);
4347 file_menu->get_popup()->add_separator();
4348
4349 file_menu->get_popup()->add_shortcut(
4350 ED_SHORTCUT_ARRAY("script_editor/history_previous", TTRC("History Previous"),
4351 { int32_t(KeyModifierMask::ALT | Key::LEFT), int32_t(Key::BACK) }),
4352 FILE_MENU_HISTORY_PREV);
4353 file_menu->get_popup()->add_shortcut(
4354 ED_SHORTCUT_ARRAY("script_editor/history_next", TTRC("History Next"),
4355 { int32_t(KeyModifierMask::ALT | Key::RIGHT), int32_t(Key::FORWARD) }),
4356 FILE_MENU_HISTORY_NEXT);
4357 ED_SHORTCUT_OVERRIDE("script_editor/history_previous", "macos", KeyModifierMask::ALT | KeyModifierMask::META | Key::LEFT);
4358 ED_SHORTCUT_OVERRIDE("script_editor/history_next", "macos", KeyModifierMask::ALT | KeyModifierMask::META | Key::RIGHT);
4359
4360 file_menu->get_popup()->add_separator();
4361
4362 theme_submenu = memnew(PopupMenu);
4363 theme_submenu->add_shortcut(ED_SHORTCUT("script_editor/import_theme", TTRC("Import Theme...")), THEME_IMPORT);
4364 theme_submenu->add_shortcut(ED_SHORTCUT("script_editor/reload_theme", TTRC("Reload Theme")), THEME_RELOAD);
4365 file_menu->get_popup()->add_submenu_node_item(TTRC("Theme"), theme_submenu, FILE_MENU_THEME_SUBMENU);
4366 theme_submenu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptEditor::_theme_option));
4367
4368 theme_submenu->add_separator();
4369 theme_submenu->add_shortcut(ED_SHORTCUT("script_editor/save_theme_as", TTRC("Save Theme As...")), THEME_SAVE_AS);
4370
4371 file_menu->get_popup()->add_separator();
4372 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_file", TTRC("Close"), KeyModifierMask::CMD_OR_CTRL | Key::W), FILE_MENU_CLOSE);
4373 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_all", TTRC("Close All")), FILE_MENU_CLOSE_ALL);
4374 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_other_tabs", TTRC("Close Other Tabs")), FILE_MENU_CLOSE_OTHER_TABS);
4375 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_tabs_below", TTRC("Close Tabs Below")), FILE_MENU_CLOSE_TABS_BELOW);
4376 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_docs", TTRC("Close Docs")), FILE_MENU_CLOSE_DOCS);
4377
4378 file_menu->get_popup()->add_separator();
4379 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/run_file", TTRC("Run"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::X), FILE_MENU_RUN);
4380
4381 file_menu->get_popup()->add_separator();
4382 file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/toggle_files_panel", TTRC("Toggle Files Panel"), KeyModifierMask::CMD_OR_CTRL | Key::BACKSLASH), FILE_MENU_TOGGLE_FILES_PANEL);
4383 file_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptEditor::_menu_option));
4384 file_menu->get_popup()->connect("about_to_popup", callable_mp(this, &ScriptEditor::_prepare_file_menu));
4385 file_menu->get_popup()->connect("popup_hide", callable_mp(this, &ScriptEditor::_file_menu_closed));
4386
4387 script_search_menu = memnew(MenuButton);
4388 script_search_menu->set_flat(false);
4389 script_search_menu->set_theme_type_variation("FlatMenuButton");
4390 script_search_menu->set_text(TTRC("Search"));
4391 script_search_menu->set_switch_on_hover(true);
4392 script_search_menu->set_shortcut_context(this);
4393 script_search_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptEditor::_menu_option));
4394 menu_hb->add_child(script_search_menu);
4395
4396 MenuButton *debug_menu_btn = memnew(MenuButton);
4397 debug_menu_btn->set_flat(false);
4398 debug_menu_btn->set_theme_type_variation("FlatMenuButton");
4399 menu_hb->add_child(debug_menu_btn);
4400 debug_menu_btn->hide(); // Handled by EditorDebuggerNode below.
4401
4402 EditorDebuggerNode *debugger = EditorDebuggerNode::get_singleton();
4403 debugger->set_script_debug_button(debug_menu_btn);
4404 debugger->connect("goto_script_line", callable_mp(this, &ScriptEditor::_goto_script_line));
4405 debugger->connect("set_execution", callable_mp(this, &ScriptEditor::_set_execution));
4406 debugger->connect("clear_execution", callable_mp(this, &ScriptEditor::_clear_execution));
4407 debugger->connect("breaked", callable_mp(this, &ScriptEditor::_breaked));
4408 debugger->connect("breakpoint_set_in_tree", callable_mp(this, &ScriptEditor::_set_breakpoint));
4409 debugger->connect("breakpoints_cleared_in_tree", callable_mp(this, &ScriptEditor::_clear_breakpoints));
4410
4411 script_name_label = memnew(Label);
4412 script_name_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
4413 script_name_label->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
4414 script_name_label->set_focus_mode(FOCUS_ACCESSIBILITY);
4415 script_name_label->set_h_size_flags(SIZE_EXPAND_FILL);
4416 menu_hb->add_child(script_name_label);
4417
4418 site_search = memnew(Button);
4419 site_search->set_theme_type_variation(SceneStringName(FlatButton));
4420 site_search->set_accessibility_name(TTRC("Site Search"));
4421 site_search->connect(SceneStringName(pressed), callable_mp(this, &ScriptEditor::_menu_option).bind(SEARCH_WEBSITE));
4422 menu_hb->add_child(site_search);
4423
4424 help_search = memnew(Button);
4425 help_search->set_theme_type_variation(SceneStringName(FlatButton));
4426 help_search->set_text(TTRC("Search Help"));
4427 help_search->connect(SceneStringName(pressed), callable_mp(this, &ScriptEditor::_menu_option).bind(SEARCH_HELP));
4428 menu_hb->add_child(help_search);
4429 help_search->set_tooltip_text(TTRC("Search the reference documentation."));
4430
4431 menu_hb->add_child(memnew(VSeparator));
4432
4433 script_back = memnew(Button);
4434 script_back->set_theme_type_variation(SceneStringName(FlatButton));
4435 script_back->set_tooltip_text(TTRC("Go to previous edited document."));
4436 script_back->set_shortcut(ED_GET_SHORTCUT("script_editor/history_previous"));
4437 script_back->set_disabled(true);
4438 menu_hb->add_child(script_back);
4439 script_back->connect(SceneStringName(pressed), callable_mp(this, &ScriptEditor::_history_back));
4440
4441 script_forward = memnew(Button);
4442 script_forward->set_theme_type_variation(SceneStringName(FlatButton));
4443 script_forward->set_tooltip_text(TTRC("Go to next edited document."));
4444 script_forward->set_shortcut(ED_GET_SHORTCUT("script_editor/history_next"));
4445 script_forward->set_disabled(true);
4446 menu_hb->add_child(script_forward);
4447 script_forward->connect(SceneStringName(pressed), callable_mp(this, &ScriptEditor::_history_forward));
4448
4449 menu_hb->add_child(memnew(VSeparator));
4450
4451 make_floating = memnew(ScreenSelect);
4452 make_floating->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4453 make_floating->connect("request_open_in_screen", callable_mp(window_wrapper, &WindowWrapper::enable_window_on_screen).bind(true));
4454
4455 menu_hb->add_child(make_floating);
4456 p_wrapper->connect("window_visibility_changed", callable_mp(this, &ScriptEditor::_window_changed));
4457
4458 tab_container->connect("tab_changed", callable_mp(this, &ScriptEditor::_tab_changed));
4459
4460 erase_tab_confirm = memnew(ConfirmationDialog);
4461 erase_tab_confirm->set_ok_button_text(TTRC("Save"));
4462 erase_tab_confirm->add_button(TTRC("Discard"), DisplayServer::get_singleton()->get_swap_cancel_ok(), "discard");
4463 erase_tab_confirm->connect(SceneStringName(confirmed), callable_mp(this, &ScriptEditor::_close_current_tab).bind(true, true));
4464 erase_tab_confirm->connect("custom_action", callable_mp(this, &ScriptEditor::_close_discard_current_tab));
4465 add_child(erase_tab_confirm);
4466
4467 script_create_dialog = memnew(ScriptCreateDialog);
4468 script_create_dialog->set_title(TTRC("Create Script"));
4469 add_child(script_create_dialog);
4470 script_create_dialog->connect("script_created", callable_mp(this, &ScriptEditor::_script_created));
4471
4472 file_dialog_option = -1;
4473 file_dialog = memnew(EditorFileDialog);
4474 add_child(file_dialog);
4475 file_dialog->connect("file_selected", callable_mp(this, &ScriptEditor::_file_dialog_action));
4476
4477 error_dialog = memnew(AcceptDialog);
4478 add_child(error_dialog);
4479
4480 disk_changed = memnew(ConfirmationDialog);
4481 {
4482 disk_changed->set_title(TTRC("Files have been modified outside Godot"));
4483
4484 VBoxContainer *vbc = memnew(VBoxContainer);
4485 disk_changed->add_child(vbc);
4486
4487 Label *files_are_newer_label = memnew(Label);
4488 files_are_newer_label->set_text(TTRC("The following files are newer on disk:"));
4489 vbc->add_child(files_are_newer_label);
4490
4491 disk_changed_list = memnew(Tree);
4492 disk_changed_list->set_hide_root(true);
4493 disk_changed_list->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
4494 disk_changed_list->set_accessibility_name(TTRC("The following files are newer on disk:"));
4495 disk_changed_list->set_v_size_flags(SIZE_EXPAND_FILL);
4496 vbc->add_child(disk_changed_list);
4497
4498 Label *what_action_label = memnew(Label);
4499 what_action_label->set_text(TTRC("What action should be taken?"));
4500 vbc->add_child(what_action_label);
4501
4502 disk_changed->connect(SceneStringName(confirmed), callable_mp(this, &ScriptEditor::reload_scripts).bind(false));
4503 disk_changed->set_ok_button_text(TTRC("Reload from disk"));
4504
4505 disk_changed->add_button(TTRC("Ignore external changes"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "resave");
4506 disk_changed->connect("custom_action", callable_mp(this, &ScriptEditor::_resave_scripts));
4507 }
4508
4509 add_child(disk_changed);
4510
4511 script_editor = this;
4512
4513 autosave_timer = memnew(Timer);
4514 autosave_timer->set_one_shot(false);
4515 autosave_timer->connect(SceneStringName(tree_entered), callable_mp(this, &ScriptEditor::_update_autosave_timer));
4516 autosave_timer->connect("timeout", callable_mp(this, &ScriptEditor::_autosave_scripts));
4517 add_child(autosave_timer);
4518
4519 grab_focus_block = false;
4520
4521 help_search_dialog = memnew(EditorHelpSearch);
4522 add_child(help_search_dialog);
4523 help_search_dialog->connect("go_to_help", callable_mp(this, &ScriptEditor::_help_class_goto));
4524
4525 find_in_files_dialog = memnew(FindInFilesDialog);
4526 find_in_files_dialog->connect(FindInFilesDialog::SIGNAL_FIND_REQUESTED, callable_mp(this, &ScriptEditor::_start_find_in_files).bind(false));
4527 find_in_files_dialog->connect(FindInFilesDialog::SIGNAL_REPLACE_REQUESTED, callable_mp(this, &ScriptEditor::_start_find_in_files).bind(true));
4528 add_child(find_in_files_dialog);
4529
4530 find_in_files = memnew(FindInFilesContainer);
4531 EditorDockManager::get_singleton()->add_dock(find_in_files);
4532 find_in_files->close();
4533 find_in_files->connect("result_selected", callable_mp(this, &ScriptEditor::_on_find_in_files_result_selected));
4534 find_in_files->connect("files_modified", callable_mp(this, &ScriptEditor::_on_find_in_files_modified_files));
4535
4536 history_pos = -1;
4537
4538 edit_pass = 0;
4539 trim_trailing_whitespace_on_save = EDITOR_GET("text_editor/behavior/files/trim_trailing_whitespace_on_save");
4540 trim_final_newlines_on_save = EDITOR_GET("text_editor/behavior/files/trim_final_newlines_on_save");
4541 convert_indent_on_save = EDITOR_GET("text_editor/behavior/files/convert_indent_on_save");
4542
4543 ScriptServer::edit_request_func = _open_script_request;
4544
4545 Ref<EditorJSONSyntaxHighlighter> json_syntax_highlighter;
4546 json_syntax_highlighter.instantiate();
4547 register_syntax_highlighter(json_syntax_highlighter);
4548
4549 Ref<EditorMarkdownSyntaxHighlighter> markdown_syntax_highlighter;
4550 markdown_syntax_highlighter.instantiate();
4551 register_syntax_highlighter(markdown_syntax_highlighter);
4552
4553 Ref<EditorConfigFileSyntaxHighlighter> config_file_syntax_highlighter;
4554 config_file_syntax_highlighter.instantiate();
4555 register_syntax_highlighter(config_file_syntax_highlighter);
4556
4557 _update_online_doc();
4558 }
4559
4560 void ScriptEditorPlugin::_focus_another_editor() {
4561 if (window_wrapper->get_window_enabled()) {
4562 ERR_FAIL_COND(last_editor.is_empty());
4563 EditorInterface::get_singleton()->set_main_screen_editor(last_editor);
4564 }
4565 }
4566
4567 void ScriptEditorPlugin::_save_last_editor(const String &p_editor) {
4568 if (p_editor != get_plugin_name()) {
4569 last_editor = p_editor;
4570 }
4571 }
4572
4573 void ScriptEditorPlugin::_window_visibility_changed(bool p_visible) {
4574 _focus_another_editor();
4575 if (p_visible) {
4576 script_editor->add_theme_style_override(SceneStringName(panel), script_editor->get_theme_stylebox("ScriptEditorPanelFloating", EditorStringName(EditorStyles)));
4577 } else {
4578 script_editor->add_theme_style_override(SceneStringName(panel), script_editor->get_theme_stylebox("ScriptEditorPanel", EditorStringName(EditorStyles)));
4579 }
4580 }
4581
4582 void ScriptEditorPlugin::_notification(int p_what) {
4583 switch (p_what) {
4584 case NOTIFICATION_TRANSLATION_CHANGED: {
4585 window_wrapper->set_window_title(vformat(TTR("%s - Godot Engine"), TTR("Script Editor")));
4586 } break;
4587 case NOTIFICATION_ENTER_TREE: {
4588 connect("main_screen_changed", callable_mp(this, &ScriptEditorPlugin::_save_last_editor));
4589 } break;
4590 case NOTIFICATION_EXIT_TREE: {
4591 disconnect("main_screen_changed", callable_mp(this, &ScriptEditorPlugin::_save_last_editor));
4592 } break;
4593 }
4594 }
4595
4596 bool ScriptEditorPlugin::open_in_external_editor(const String &p_path, int p_line, int p_col, bool p_ignore_project) {
4597 const String path = EDITOR_GET("text_editor/external/exec_path");
4598 if (path.is_empty()) {
4599 return false;
4600 }
4601
4602 String flags = EDITOR_GET("text_editor/external/exec_flags");
4603
4604 List<String> args;
4605 bool has_file_flag = false;
4606
4607 if (!flags.is_empty()) {
4608 flags = flags.replacen("{line}", itos(MAX(p_line + 1, 1)));
4609 flags = flags.replacen("{col}", itos(p_col + 1));
4610 flags = flags.strip_edges().replace("\\\\", "\\");
4611
4612 int from = 0;
4613 int num_chars = 0;
4614 bool inside_quotes = false;
4615
4616 for (int i = 0; i < flags.size(); i++) {
4617 if (flags[i] == '"' && (!i || flags[i - 1] != '\\')) {
4618 if (!inside_quotes) {
4619 from++;
4620 }
4621 inside_quotes = !inside_quotes;
4622
4623 } else if (flags[i] == '\0' || (!inside_quotes && flags[i] == ' ')) {
4624 String arg = flags.substr(from, num_chars);
4625 if (arg.contains("{file}")) {
4626 has_file_flag = true;
4627 }
4628
4629 // Do path replacement here, else there will be issues with spaces and quotes
4630 if (p_ignore_project) {
4631 arg = arg.replacen("{project}", String());
4632 } else {
4633 arg = arg.replacen("{project}", ProjectSettings::get_singleton()->get_resource_path());
4634 }
4635 arg = arg.replacen("{file}", p_path);
4636 args.push_back(arg);
4637
4638 from = i + 1;
4639 num_chars = 0;
4640 } else {
4641 num_chars++;
4642 }
4643 }
4644 }
4645
4646 // Default to passing script path if no {file} flag is specified.
4647 if (!has_file_flag) {
4648 args.push_back(p_path);
4649 }
4650 return OS::get_singleton()->create_process(path, args) == OK;
4651 }
4652
4653 void ScriptEditorPlugin::edit(Object *p_object) {
4654 if (Object::cast_to<Script>(p_object)) {
4655 Script *p_script = Object::cast_to<Script>(p_object);
4656 String res_path = p_script->get_path().get_slice("::", 0);
4657
4658 if (p_script->is_built_in() && !res_path.is_empty()) {
4659 EditorNode::get_singleton()->load_scene_or_resource(res_path, false, false);
4660 }
4661 script_editor->edit(p_script);
4662 } else if (Object::cast_to<JSON>(p_object)) {
4663 script_editor->edit(Object::cast_to<JSON>(p_object));
4664 } else if (Object::cast_to<TextFile>(p_object)) {
4665 script_editor->edit(Object::cast_to<TextFile>(p_object));
4666 }
4667 }
4668
4669 bool ScriptEditorPlugin::handles(Object *p_object) const {
4670 if (Object::cast_to<TextFile>(p_object)) {
4671 return true;
4672 }
4673
4674 if (Object::cast_to<Script>(p_object)) {
4675 return true;
4676 }
4677
4678 if (Object::cast_to<JSON>(p_object)) {
4679 // This is here to stop resource files of class JSON from getting confused
4680 // with json files and being opened in the text editor.
4681 if (Object::cast_to<JSON>(p_object)->get_path().get_extension().to_lower() == "json") {
4682 return true;
4683 }
4684 }
4685
4686 return p_object->is_class("Script");
4687 }
4688
4689 void ScriptEditorPlugin::make_visible(bool p_visible) {
4690 if (p_visible) {
4691 window_wrapper->show();
4692 script_editor->ensure_select_current();
4693 } else {
4694 window_wrapper->hide();
4695 }
4696 }
4697
4698 void ScriptEditorPlugin::selected_notify() {
4699 script_editor->ensure_select_current();
4700 _focus_another_editor();
4701 }
4702
4703 String ScriptEditorPlugin::get_unsaved_status(const String &p_for_scene) const {
4704 const PackedStringArray unsaved_scripts = script_editor->get_unsaved_scripts();
4705 if (unsaved_scripts.is_empty()) {
4706 return String();
4707 }
4708
4709 PackedStringArray message;
4710 if (!p_for_scene.is_empty()) {
4711 PackedStringArray unsaved_built_in_scripts;
4712
4713 const String scene_file = p_for_scene.get_file();
4714 for (const String &E : unsaved_scripts) {
4715 if (!E.is_resource_file() && E.contains(scene_file)) {
4716 unsaved_built_in_scripts.append(E);
4717 }
4718 }
4719
4720 if (unsaved_built_in_scripts.is_empty()) {
4721 return String();
4722 } else {
4723 message.resize(unsaved_built_in_scripts.size() + 1);
4724 message.write[0] = TTR("There are unsaved changes in the following built-in script(s):");
4725
4726 int i = 1;
4727 for (const String &E : unsaved_built_in_scripts) {
4728 message.write[i] = E.trim_suffix("(*)");
4729 i++;
4730 }
4731 return String("\n").join(message);
4732 }
4733 }
4734
4735 message.resize(unsaved_scripts.size() + 1);
4736 message.write[0] = TTR("Save changes to the following script(s) before quitting?");
4737
4738 int i = 1;
4739 for (const String &E : unsaved_scripts) {
4740 message.write[i] = E.trim_suffix("(*)");
4741 i++;
4742 }
4743 return String("\n").join(message);
4744 }
4745
4746 void ScriptEditorPlugin::save_external_data() {
4747 if (!EditorNode::get_singleton()->is_exiting()) {
4748 script_editor->save_all_scripts();
4749 }
4750 }
4751
4752 void ScriptEditorPlugin::apply_changes() {
4753 script_editor->apply_scripts();
4754 }
4755
4756 void ScriptEditorPlugin::set_window_layout(Ref<ConfigFile> p_layout) {
4757 script_editor->set_window_layout(p_layout);
4758
4759 if (EDITOR_GET("interface/multi_window/restore_windows_on_load") && window_wrapper->is_window_available() && p_layout->has_section_key("ScriptEditor", "window_rect")) {
4760 window_wrapper->restore_window_from_saved_position(
4761 p_layout->get_value("ScriptEditor", "window_rect", Rect2i()),
4762 p_layout->get_value("ScriptEditor", "window_screen", -1),
4763 p_layout->get_value("ScriptEditor", "window_screen_rect", Rect2i()));
4764 } else {
4765 window_wrapper->set_window_enabled(false);
4766 }
4767 }
4768
4769 void ScriptEditorPlugin::get_window_layout(Ref<ConfigFile> p_layout) {
4770 script_editor->get_window_layout(p_layout);
4771
4772 if (window_wrapper->get_window_enabled()) {
4773 p_layout->set_value("ScriptEditor", "window_rect", window_wrapper->get_window_rect());
4774 int screen = window_wrapper->get_window_screen();
4775 p_layout->set_value("ScriptEditor", "window_screen", screen);
4776 p_layout->set_value("ScriptEditor", "window_screen_rect", DisplayServer::get_singleton()->screen_get_usable_rect(screen));
4777
4778 } else {
4779 if (p_layout->has_section_key("ScriptEditor", "window_rect")) {
4780 p_layout->erase_section_key("ScriptEditor", "window_rect");
4781 }
4782 if (p_layout->has_section_key("ScriptEditor", "window_screen")) {
4783 p_layout->erase_section_key("ScriptEditor", "window_screen");
4784 }
4785 if (p_layout->has_section_key("ScriptEditor", "window_screen_rect")) {
4786 p_layout->erase_section_key("ScriptEditor", "window_screen_rect");
4787 }
4788 }
4789 }
4790
4791 void ScriptEditorPlugin::get_breakpoints(List<String> *p_breakpoints) {
4792 script_editor->get_breakpoints(p_breakpoints);
4793 }
4794
4795 void ScriptEditorPlugin::edited_scene_changed() {
4796 script_editor->edited_scene_changed();
4797 }
4798
4799 ScriptEditorPlugin::ScriptEditorPlugin() {
4800 ED_SHORTCUT("script_editor/reopen_closed_script", TTRC("Reopen Closed Script"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::T);
4801 ED_SHORTCUT("script_editor/clear_recent", TTRC("Clear Recent Scripts"));
4802 ED_SHORTCUT("script_editor/replace_in_files", TTRC("Replace in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::R);
4803
4804 ED_SHORTCUT("script_text_editor/convert_to_uppercase", TTRC("Uppercase"), KeyModifierMask::SHIFT | Key::F4);
4805 ED_SHORTCUT("script_text_editor/convert_to_lowercase", TTRC("Lowercase"), KeyModifierMask::SHIFT | Key::F5);
4806 ED_SHORTCUT("script_text_editor/capitalize", TTRC("Capitalize"), KeyModifierMask::SHIFT | Key::F6);
4807
4808 window_wrapper = memnew(WindowWrapper);
4809 window_wrapper->set_margins_enabled(true);
4810
4811 script_editor = memnew(ScriptEditor(window_wrapper));
4812 Ref<Shortcut> make_floating_shortcut = ED_SHORTCUT_AND_COMMAND("script_editor/make_floating", TTRC("Make Floating"));
4813 window_wrapper->set_wrapped_control(script_editor, make_floating_shortcut);
4814
4815 EditorNode::get_singleton()->get_editor_main_screen()->get_control()->add_child(window_wrapper);
4816 window_wrapper->set_v_size_flags(Control::SIZE_EXPAND_FILL);
4817 window_wrapper->hide();
4818 window_wrapper->connect("window_visibility_changed", callable_mp(this, &ScriptEditorPlugin::_window_visibility_changed));
4819
4820 ScriptServer::set_reload_scripts_on_save(EDITOR_GET("text_editor/behavior/files/auto_reload_and_parse_scripts_on_save"));
4821 }