Skip to content
0.2.0-dev Download ZIP
9910 lines ·382.5 KB Raw
1/**************************************************************************/
2/* editor_node.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 "editor_node.h"
32
33#include "core/config/engine.h"
34#include "core/config/project_settings.h"
35#include "core/extension/gdextension_manager.h"
36#include "core/input/input.h"
37#include "core/io/config_file.h"
38#include "core/io/file_access.h"
39#include "core/io/image.h"
40#include "core/io/missing_resource.h"
41#include "core/io/resource_importer.h"
42#include "core/io/resource_loader.h"
43#include "core/io/resource_saver.h"
44#include "core/object/callable_mp.h"
45#include "core/object/class_db.h"
46#include "core/os/keyboard.h"
47#include "core/os/os.h"
48#include "core/os/time.h"
49#include "core/string/print_string.h"
50#include "core/string/translation_server.h"
51#include "core/version.h"
52#include "editor/animation/animation_player_editor_plugin.h"
53#include "editor/asset_library/asset_library_editor_plugin.h"
54#include "editor/audio/audio_stream_editor_plugin.h"
55#include "editor/audio/audio_stream_preview.h"
56#include "editor/audio/editor_audio_buses.h"
57#include "editor/debugger/debugger_editor_plugin.h"
58#include "editor/debugger/editor_debugger_node.h"
59#include "editor/debugger/script_editor_debugger.h"
60#include "editor/doc/editor_help.h"
61#include "editor/docks/editor_dock_manager.h"
62#include "editor/docks/filesystem_dock.h"
63#include "editor/docks/groups_dock.h"
64#include "editor/docks/history_dock.h"
65#include "editor/docks/import_dock.h"
66#include "editor/docks/inspector_dock.h"
67#include "editor/docks/scene_tree_dock.h"
68#include "editor/docks/signals_dock.h"
69#include "editor/editor_data.h"
70#include "editor/editor_interface.h"
71#include "editor/editor_log.h"
72#include "editor/editor_main_screen.h"
73#include "editor/editor_string_names.h"
74#include "editor/editor_undo_redo_manager.h"
75#include "editor/export/dedicated_server_export_plugin.h"
76#include "editor/export/editor_export.h"
77#include "editor/export/export_template_manager.h"
78#include "editor/export/gdextension_export_plugin.h"
79#include "editor/export/project_export.h"
80#include "editor/export/project_zip_packer.h"
81#include "editor/export/register_exporters.h"
82#include "editor/file_system/dependency_editor.h"
83#include "editor/file_system/editor_paths.h"
84#include "editor/gui/editor_about.h"
85#include "editor/gui/editor_bottom_panel.h"
86#include "editor/gui/editor_file_dialog.h"
87#include "editor/gui/editor_icon_manager.h"
88#include "editor/gui/editor_quick_open_dialog.h"
89#include "editor/gui/editor_title_bar.h"
90#include "editor/gui/editor_toaster.h"
91#include "editor/gui/progress_dialog.h"
92#include "editor/gui/window_wrapper.h"
93#include "editor/import/3d/editor_import_collada.h"
94#include "editor/import/3d/resource_importer_obj.h"
95#include "editor/import/3d/resource_importer_scene.h"
96#include "editor/import/3d/scene_import_settings.h"
97#include "editor/import/audio_stream_import_settings.h"
98#include "editor/import/dynamic_font_import_settings.h"
99#include "editor/import/fbx_importer_manager.h"
100#include "editor/import/resource_importer_bitmask.h"
101#include "editor/import/resource_importer_bmfont.h"
102#include "editor/import/resource_importer_csv_translation.h"
103#include "editor/import/resource_importer_dynamic_font.h"
104#include "editor/import/resource_importer_image.h"
105#include "editor/import/resource_importer_imagefont.h"
106#include "editor/import/resource_importer_layered_texture.h"
107#include "editor/import/resource_importer_shader_file.h"
108#include "editor/import/resource_importer_streamed_texture.h"
109#include "editor/import/resource_importer_svg.h"
110#include "editor/import/resource_importer_texture.h"
111#include "editor/import/resource_importer_texture_atlas.h"
112#include "editor/import/resource_importer_wav.h"
113#include "editor/inspector/editor_context_menu_plugin.h"
114#include "editor/inspector/editor_inspector.h"
115#include "editor/inspector/editor_preview_plugins.h"
116#include "editor/inspector/editor_properties.h"
117#include "editor/inspector/editor_property_name_processor.h"
118#include "editor/inspector/editor_resource_picker.h"
119#include "editor/inspector/editor_resource_preview.h"
120#include "editor/inspector/multi_node_edit.h"
121#include "editor/plugins/editor_plugin.h"
122#include "editor/plugins/editor_plugin_list.h"
123#include "editor/plugins/editor_resource_conversion_plugin.h"
124#include "editor/plugins/plugin_config_dialog.h"
125#include "editor/project_upgrade/project_upgrade_tool.h"
126#include "editor/run/editor_run.h"
127#include "editor/run/editor_run_bar.h"
128#include "editor/run/game_view_plugin.h"
129#include "editor/scene/3d/material_3d_conversion_plugins.h"
130#include "editor/scene/3d/mesh_library_editor_plugin.h"
131#include "editor/scene/3d/node_3d_editor_plugin.h"
132#include "editor/scene/3d/node_3d_editor_viewport.h"
133#include "editor/scene/3d/root_motion_editor_plugin.h"
134#include "editor/scene/canvas_item_editor_plugin.h"
135#include "editor/scene/editor_scene_tabs.h"
136#include "editor/scene/material_editor_plugin.h"
137#include "editor/scene/particle_process_material_editor_plugin.h"
138#include "editor/script/editor_script.h"
139#include "editor/script/find_in_files.h"
140#include "editor/script/script_text_editor.h"
141#include "editor/script/text_editor.h"
142#include "editor/settings/editor_build_profile.h"
143#include "editor/settings/editor_command_palette.h"
144#include "editor/settings/editor_feature_profile.h"
145#include "editor/settings/editor_layouts_dialog.h"
146#include "editor/settings/editor_settings.h"
147#include "editor/settings/editor_settings_dialog.h"
148#include "editor/settings/project_settings_editor.h"
149#include "editor/shader/editor_native_shader_source_visualizer.h"
150#include "editor/shader/shader_editor_plugin.h"
151#include "editor/shader/shader_text_editor.h"
152#include "editor/themes/editor_color_map.h"
153#include "editor/themes/editor_scale.h"
154#include "editor/themes/editor_theme_manager.h"
155#include "editor/translations/editor_translation_parser.h"
156#include "editor/translations/packed_scene_translation_parser_plugin.h"
157#include "editor/version_control/version_control_editor_plugin.h"
158#include "main/main.h"
159#include "scene/2d/node_2d.h"
160#include "scene/3d/bone_attachment_3d.h"
161#include "scene/animation/animation_tree.h"
162#include "scene/gui/color_picker.h"
163#include "scene/gui/control.h"
164#include "scene/gui/dialogs.h"
165#include "scene/gui/file_dialog.h"
166#include "scene/gui/menu_bar.h"
167#include "scene/gui/menu_button.h"
168#include "scene/gui/panel.h"
169#include "scene/gui/popup.h"
170#include "scene/gui/rich_text_label.h"
171#include "scene/gui/split_container.h"
172#include "scene/gui/tab_container.h"
173#include "scene/main/scene_tree.h"
174#include "scene/main/timer.h"
175#include "scene/main/window.h"
176#include "scene/property_utils.h"
177#include "scene/resources/3d/mesh_library.h"
178#include "scene/resources/dpi_texture.h"
179#include "scene/resources/image_texture.h"
180#include "scene/resources/packed_scene.h"
181#include "scene/resources/portable_compressed_texture.h"
182#include "scene/theme/theme_db.h"
183#include "servers/audio/audio_server.h"
184#include "servers/audio/audio_server_enums.h"
185#include "servers/display/display_server.h"
186#include "servers/display/display_server_enums.h"
187#include "servers/navigation_2d/navigation_server_2d.h"
188#include "servers/navigation_3d/navigation_server_3d.h"
189#include "servers/physics_3d/physics_server_3d_manager.h"
190#include "servers/rendering/rendering_device.h"
191#include "servers/rendering/rendering_server.h"
192
193#ifdef RD_ENABLED
194#include "editor/export/shader_baker/shader_baker_export_plugin.h"
195
196#ifdef VULKAN_ENABLED
197#include "editor/shader/shader_baker/shader_baker_export_plugin_platform_vulkan.h"
198#endif
199
200#ifdef D3D12_ENABLED
201#include "editor/shader/shader_baker/shader_baker_export_plugin_platform_d3d12.h"
202#endif
203
204#ifdef METAL_ENABLED
205#include "editor/shader/shader_baker/shader_baker_export_plugin_platform_metal.h"
206#endif
207#endif // RD_ENABLED
208
209#ifndef PHYSICS_2D_DISABLED
210#include "servers/physics_2d/physics_server_2d.h"
211#endif // PHYSICS_2D_DISABLED
212
213#ifndef PHYSICS_3D_DISABLED
214#include "servers/physics_3d/physics_server_3d.h"
215#endif // PHYSICS_3D_DISABLED
216
217#ifdef ANDROID_ENABLED
218#include "editor/gui/touch_actions_panel.h"
219#else
220#include "editor/export/android_sdk_manager.h"
221#endif // ANDROID_ENABLED
222
223#include "modules/modules_enabled.gen.h" // For gdscript, mono.
224
225#include <cstdlib>
226
227#ifdef WEB_ENABLED
228extern "C" {
229extern void godot_js_os_download_buffer(const uint8_t *p_buf, int p_buf_size, const char *p_name, const char *p_mime);
230}
231#endif // WEB_ENABLED
232
233EditorNode *EditorNode::singleton = nullptr;
234
235static const String EDITOR_NODE_CONFIG_SECTION = "EditorNode";
236
237static const String ANDROID_BUILD_TEMPLATE_ALREADY_INSTALLED_MESSAGE = TTRC("The Android build template is already installed.");
238static const String REMOVE_ANDROID_BUILD_TEMPLATE_MESSAGE = TTRC("Remove the \"%s\" directory manually, or enable automatic deletion in the Editor Settings (Export > Android > Build > Automatically Delete Build Directory) before attempting this operation again.");
239static const String INSTALL_ANDROID_BUILD_TEMPLATE_MESSAGE = TTRC("This will set up your project for gradle Android builds by installing the source template to \"%s\".\nNote that in order to make gradle builds instead of using pre-built APKs, the \"Use Gradle Build\" option should be enabled in the Android export preset.");
240
241constexpr int LARGE_RESOURCE_WARNING_SIZE_THRESHOLD = 512'000; // 500 KB
242
243bool EditorProgress::step(const String &p_state, int p_step, bool p_force_refresh) {
244 if (!force_background && Thread::is_main_thread()) {
245 return EditorNode::progress_task_step(task, p_state, p_step, p_force_refresh);
246 } else {
247 EditorNode::progress_task_step_bg(task, p_step);
248 return false;
249 }
250}
251
252EditorProgress::EditorProgress(const String &p_task, const String &p_label, int p_amount, bool p_can_cancel, bool p_force_background) {
253 if (!p_force_background && Thread::is_main_thread()) {
254 EditorNode::progress_add_task(p_task, p_label, p_amount, p_can_cancel);
255 } else {
256 EditorNode::progress_add_task_bg(p_task, p_label, p_amount);
257 }
258 task = p_task;
259 force_background = p_force_background;
260}
261
262EditorProgress::~EditorProgress() {
263 if (!force_background && Thread::is_main_thread()) {
264 EditorNode::progress_end_task(task);
265 } else {
266 EditorNode::progress_end_task_bg(task);
267 }
268}
269
270void EditorNode::disambiguate_filenames(const Vector<String> p_full_paths, Vector<String> &r_filenames) {
271 ERR_FAIL_COND_MSG(p_full_paths.size() != r_filenames.size(), vformat("disambiguate_filenames requires two string vectors of same length (%d != %d).", p_full_paths.size(), r_filenames.size()));
272
273 // Keep track of a list of "index sets," i.e. sets of indices
274 // within disambiguated_scene_names which contain the same name.
275 Vector<RBSet<int>> index_sets;
276 HashMap<String, int> scene_name_to_set_index;
277 for (int i = 0; i < r_filenames.size(); i++) {
278 const String &scene_name = r_filenames[i];
279 if (!scene_name_to_set_index.has(scene_name)) {
280 index_sets.append(RBSet<int>());
281 scene_name_to_set_index.insert(r_filenames[i], index_sets.size() - 1);
282 }
283 index_sets.write[scene_name_to_set_index[scene_name]].insert(i);
284 }
285
286 // For each index set with a size > 1, we need to disambiguate.
287 for (int i = 0; i < index_sets.size(); i++) {
288 RBSet<int> iset(index_sets[i]);
289 while (iset.size() > 1) {
290 // Append the parent folder to each scene name.
291 for (const int &E : iset) {
292 int set_idx = E;
293 String scene_name = r_filenames[set_idx];
294 String full_path = p_full_paths[set_idx];
295
296 // Get rid of file extensions and res:// prefixes.
297 scene_name = scene_name.get_basename();
298 if (full_path.begins_with("res://")) {
299 full_path = full_path.substr(6);
300 }
301 full_path = full_path.get_basename();
302
303 // Normalize trailing slashes when normalizing directory names.
304 scene_name = scene_name.trim_suffix("/");
305 full_path = full_path.trim_suffix("/");
306
307 int scene_name_size = scene_name.size();
308 int full_path_size = full_path.size();
309 int difference = full_path_size - scene_name_size;
310
311 // Find just the parent folder of the current path and append it.
312 // If the current name is foo.tscn, and the full path is /some/folder/foo.tscn
313 // then slash_idx is the second '/', so that we select just "folder", and
314 // append that to yield "folder/foo.tscn".
315 if (difference > 0) {
316 String parent = full_path.substr(0, difference);
317 int slash_idx = parent.rfind_char('/');
318 slash_idx = parent.rfind_char('/', slash_idx - 1);
319 parent = (slash_idx >= 0 && parent.length() > 1) ? parent.substr(slash_idx + 1) : parent;
320 r_filenames.write[set_idx] = parent + r_filenames[set_idx];
321 }
322 }
323
324 // Loop back through scene names and remove non-ambiguous names.
325 bool can_proceed = false;
326 RBSet<int>::Element *E = iset.front();
327 while (E) {
328 String scene_name = r_filenames[E->get()];
329 bool duplicate_found = false;
330 for (const int &F : iset) {
331 if (E->get() == F) {
332 continue;
333 }
334 const String &other_scene_name = r_filenames[F];
335 if (other_scene_name == scene_name) {
336 duplicate_found = true;
337 break;
338 }
339 }
340
341 RBSet<int>::Element *to_erase = duplicate_found ? nullptr : E;
342
343 // We need to check that we could actually append anymore names
344 // if we wanted to for disambiguation. If we can't, then we have
345 // to abort even with ambiguous names. We clean the full path
346 // and the scene name first to remove extensions so that this
347 // comparison actually works.
348 String path = p_full_paths[E->get()];
349
350 // Get rid of file extensions and res:// prefixes.
351 scene_name = scene_name.get_basename();
352 if (path.begins_with("res://")) {
353 path = path.substr(6);
354 }
355 path = path.get_basename();
356
357 // Normalize trailing slashes when normalizing directory names.
358 scene_name = scene_name.trim_suffix("/");
359 path = path.trim_suffix("/");
360
361 // We can proceed if the full path is longer than the scene name,
362 // meaning that there is at least one more parent folder we can
363 // tack onto the name.
364 can_proceed = can_proceed || (path.size() - scene_name.size()) >= 1;
365
366 E = E->next();
367 if (to_erase) {
368 iset.erase(to_erase);
369 }
370 }
371
372 if (!can_proceed) {
373 break;
374 }
375 }
376 }
377}
378
379void EditorNode::_version_control_menu_option(int p_idx) {
380 switch (vcs_actions_menu->get_item_id(p_idx)) {
381 case VCS_METADATA: {
382 VersionControlEditorPlugin::get_singleton()->popup_vcs_metadata_dialog();
383 } break;
384 case VCS_SETTINGS: {
385 VersionControlEditorPlugin::get_singleton()->popup_vcs_set_up_dialog(gui_base);
386 } break;
387 }
388}
389
390void EditorNode::_update_title() {
391 const String appname = GLOBAL_GET("application/config/name");
392 String title = (appname.is_empty() ? TTR("Unnamed Project") : appname);
393 const String edited = editor_data.get_edited_scene_root() ? editor_data.get_edited_scene_root()->get_scene_file_path() : String();
394 if (!edited.is_empty()) {
395 // Display the edited scene name before the program name so that it can be seen in the OS task bar.
396 title = vformat("%s - %s", edited.get_file(), title);
397 }
398 if (unsaved_cache) {
399 // Display the "modified" mark before anything else so that it can always be seen in the OS task bar.
400 title = vformat("(*) %s", title);
401 }
402 DisplayServer::get_singleton()->window_set_title(title + String(" - ") + GODOT_VERSION_NAME);
403 if (project_title) {
404 project_title->set_text(title);
405 }
406}
407
408void EditorNode::_update_unsaved_cache() {
409 bool is_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY) ||
410 EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_current_edited_scene_history_id());
411
412 if (unsaved_cache != is_unsaved) {
413 unsaved_cache = is_unsaved;
414 _update_title();
415 }
416}
417
418void EditorNode::input(const Ref<InputEvent> &p_event) {
419 // EditorNode::get_singleton()->set_process_input is set to true in ProgressDialog
420 // only when the progress dialog is visible.
421 // We need to discard all key events to disable all shortcuts while the progress
422 // dialog is displayed, simulating an exclusive popup. Mouse events are
423 // captured by a full-screen container in front of the EditorNode in ProgressDialog,
424 // allowing interaction with the actual dialog where a Cancel button may be visible.
425 Ref<InputEventKey> k = p_event;
426 if (k.is_valid()) {
427 get_tree()->get_root()->set_input_as_handled();
428 }
429}
430
431void EditorNode::shortcut_input(const Ref<InputEvent> &p_event) {
432 ERR_FAIL_COND(p_event.is_null());
433
434 Ref<InputEventKey> k = p_event;
435 if ((k.is_valid() && k->is_pressed() && !k->is_echo()) || Object::cast_to<InputEventShortcut>(*p_event)) {
436 bool is_handled = true;
437 if (ED_IS_SHORTCUT("editor/filter_files", p_event)) {
438 FileSystemDock::get_singleton()->focus_on_filter();
439 } else if (ED_IS_SHORTCUT("editor/editor_help", p_event)) {
440 emit_signal(SNAME("request_help_search"), "");
441 } else if (ED_IS_SHORTCUT("editor/editor_next", p_event)) {
442 editor_main_screen->select_next();
443 } else if (ED_IS_SHORTCUT("editor/editor_prev", p_event)) {
444 editor_main_screen->select_prev();
445 } else if (ED_IS_SHORTCUT("editor/command_palette", p_event)) {
446 _open_command_palette();
447 } else if (ED_IS_SHORTCUT("editor/toggle_last_opened_bottom_panel", p_event)) {
448 bottom_panel->toggle_last_opened_bottom_panel();
449 } else if (ED_IS_SHORTCUT("editor/toggle_selected_nodes_visibility", p_event)) {
450 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
451 undo_redo->create_action(TTR("Toggle Selected Node(s) Visibility"));
452 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
453
454 for (Node *E : selection) {
455 Node *node_with_visibility;
456 node_with_visibility = Object::cast_to<CanvasItem>(E);
457 if (!node_with_visibility || !node_with_visibility->is_inside_tree()) {
458 node_with_visibility = Object::cast_to<Node3D>(E);
459 if (!node_with_visibility || !node_with_visibility->is_inside_tree()) {
460 continue;
461 }
462 }
463
464 undo_redo->add_do_method(node_with_visibility, "set_visible", !node_with_visibility->get("visible"));
465 undo_redo->add_undo_method(node_with_visibility, "set_visible", node_with_visibility->get("visible"));
466 }
467
468 undo_redo->commit_action();
469 } else {
470 is_handled = false;
471 }
472
473 if (is_handled) {
474 get_tree()->get_root()->set_input_as_handled();
475 }
476 }
477}
478
479void EditorNode::_update_vsync_mode() {
480 const DisplayServerEnums::VSyncMode window_vsync_mode = DisplayServerEnums::VSyncMode(int(EDITOR_GET("interface/editor/display/vsync_mode")));
481 DisplayServer::get_singleton()->window_set_vsync_mode(window_vsync_mode);
482}
483
484void EditorNode::_update_from_settings() {
485 if (!is_inside_tree()) {
486 return;
487 }
488 _update_title();
489
490 int current_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
491 if (current_filter != scene_root->get_default_canvas_item_texture_filter()) {
492 Viewport::DefaultCanvasItemTextureFilter tf = (Viewport::DefaultCanvasItemTextureFilter)current_filter;
493 scene_root->set_default_canvas_item_texture_filter(tf);
494 }
495 int current_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
496 if (current_repeat != scene_root->get_default_canvas_item_texture_repeat()) {
497 Viewport::DefaultCanvasItemTextureRepeat tr = (Viewport::DefaultCanvasItemTextureRepeat)current_repeat;
498 scene_root->set_default_canvas_item_texture_repeat(tr);
499 }
500 String current_fallback_locale = GLOBAL_GET("internationalization/locale/fallback");
501 if (current_fallback_locale != TranslationServer::get_singleton()->get_fallback_locale()) {
502 TranslationServer::get_singleton()->set_fallback_locale(current_fallback_locale);
503 Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_main_domain();
504 if (!domain->is_enabled()) {
505 domain->set_locale_override(current_fallback_locale);
506 }
507 scene_root->propagate_notification(Control::NOTIFICATION_LAYOUT_DIRECTION_CHANGED);
508 }
509
510 RSE::DOFBokehShape dof_shape = RSE::DOFBokehShape(int(GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_bokeh_shape")));
511 RS::get_singleton()->camera_attributes_set_dof_blur_bokeh_shape(dof_shape);
512 RSE::DOFBlurQuality dof_quality = RSE::DOFBlurQuality(int(GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_bokeh_quality")));
513 bool dof_jitter = GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_use_jitter");
514 RS::get_singleton()->camera_attributes_set_dof_blur_quality(dof_quality, dof_jitter);
515 RS::get_singleton()->environment_set_ssao_quality(RSE::EnvironmentSSAOQuality(int(GLOBAL_GET("rendering/environment/ssao/quality"))), GLOBAL_GET("rendering/environment/ssao/half_size"), GLOBAL_GET("rendering/environment/ssao/adaptive_target"), GLOBAL_GET("rendering/environment/ssao/blur_passes"), GLOBAL_GET("rendering/environment/ssao/fadeout_from"), GLOBAL_GET("rendering/environment/ssao/fadeout_to"));
516 RS::get_singleton()->screen_space_roughness_limiter_set_active(GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/enabled"), GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/amount"), GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/limit"));
517 bool glow_bicubic = int(GLOBAL_GET("rendering/environment/glow/upscale_mode")) > 0;
518 RS::get_singleton()->environment_set_ssil_quality(RSE::EnvironmentSSILQuality(int(GLOBAL_GET("rendering/environment/ssil/quality"))), GLOBAL_GET("rendering/environment/ssil/half_size"), GLOBAL_GET("rendering/environment/ssil/adaptive_target"), GLOBAL_GET("rendering/environment/ssil/blur_passes"), GLOBAL_GET("rendering/environment/ssil/fadeout_from"), GLOBAL_GET("rendering/environment/ssil/fadeout_to"));
519 RS::get_singleton()->environment_glow_set_use_bicubic_upscale(glow_bicubic);
520 RS::get_singleton()->environment_set_ssr_half_size(GLOBAL_GET("rendering/environment/screen_space_reflection/half_size"));
521 RSE::SubSurfaceScatteringQuality sss_quality = RSE::SubSurfaceScatteringQuality(int(GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_quality")));
522 RS::get_singleton()->sub_surface_scattering_set_quality(sss_quality);
523 float sss_scale = GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_scale");
524 float sss_depth_scale = GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_depth_scale");
525 RS::get_singleton()->sub_surface_scattering_set_scale(sss_scale, sss_depth_scale);
526
527 uint32_t directional_shadow_size = GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/size");
528 uint32_t directional_shadow_16_bits = GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/16_bits");
529 RS::get_singleton()->directional_shadow_atlas_set_size(directional_shadow_size, directional_shadow_16_bits);
530
531 RSE::ShadowQuality shadows_quality = RSE::ShadowQuality(int(GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality")));
532 RS::get_singleton()->positional_soft_shadow_filter_set_quality(shadows_quality);
533 RSE::ShadowQuality directional_shadow_quality = RSE::ShadowQuality(int(GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality")));
534 RS::get_singleton()->directional_soft_shadow_filter_set_quality(directional_shadow_quality);
535 float probe_update_speed = GLOBAL_GET("rendering/lightmapping/probe_capture/update_speed");
536 RS::get_singleton()->lightmap_set_probe_capture_update_speed(probe_update_speed);
537 RSE::EnvironmentSDFGIFramesToConverge frames_to_converge = RSE::EnvironmentSDFGIFramesToConverge(int(GLOBAL_GET("rendering/global_illumination/sdfgi/frames_to_converge")));
538 RS::get_singleton()->environment_set_sdfgi_frames_to_converge(frames_to_converge);
539 RSE::EnvironmentSDFGIRayCount ray_count = RSE::EnvironmentSDFGIRayCount(int(GLOBAL_GET("rendering/global_illumination/sdfgi/probe_ray_count")));
540 RS::get_singleton()->environment_set_sdfgi_ray_count(ray_count);
541 RSE::VoxelGIQuality voxel_gi_quality = RSE::VoxelGIQuality(int(GLOBAL_GET("rendering/global_illumination/voxel_gi/quality")));
542 RS::get_singleton()->voxel_gi_set_quality(voxel_gi_quality);
543 RS::get_singleton()->environment_set_volumetric_fog_volume_size(GLOBAL_GET("rendering/environment/volumetric_fog/volume_size"), GLOBAL_GET("rendering/environment/volumetric_fog/volume_depth"));
544 RS::get_singleton()->environment_set_volumetric_fog_filter_active(bool(GLOBAL_GET("rendering/environment/volumetric_fog/use_filter")));
545 RS::get_singleton()->canvas_set_shadow_texture_size(GLOBAL_GET("rendering/2d/shadow_atlas/size"));
546
547 bool use_half_res_gi = GLOBAL_GET("rendering/global_illumination/gi/use_half_resolution");
548 RS::get_singleton()->gi_set_use_half_resolution(use_half_res_gi);
549
550 bool snap_2d_transforms = GLOBAL_GET("rendering/2d/snap/snap_2d_transforms_to_pixel");
551 scene_root->set_snap_2d_transforms_to_pixel(snap_2d_transforms);
552 bool snap_2d_vertices = GLOBAL_GET("rendering/2d/snap/snap_2d_vertices_to_pixel");
553 scene_root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);
554
555 Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_GET("rendering/2d/sdf/oversize")));
556 scene_root->set_sdf_oversize(sdf_oversize);
557 Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_GET("rendering/2d/sdf/scale")));
558 scene_root->set_sdf_scale(sdf_scale);
559
560 Viewport::MSAA msaa = Viewport::MSAA(int(GLOBAL_GET("rendering/anti_aliasing/quality/msaa_2d")));
561 scene_root->set_msaa_2d(msaa);
562
563 // 2D doesn't use a dedicated SubViewport like 3D does, so we apply it on the root viewport instead.
564 bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
565 scene_root->set_use_debanding(use_debanding);
566 get_viewport()->set_use_debanding(use_debanding);
567
568 // Enable HDR if requested.
569 const bool hdr_requested = GLOBAL_GET("display/window/hdr/request_hdr_output");
570 DisplayServer::get_singleton()->window_request_hdr_output(hdr_requested);
571
572 const bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
573 scene_root->set_use_hdr_2d(use_hdr_2d || hdr_requested);
574 get_viewport()->set_use_hdr_2d(use_hdr_2d || hdr_requested);
575
576 if (hdr_requested && !use_hdr_2d) {
577 WARN_PRINT_ED("HDR 2D was automatically enabled because HDR output was requested in project settings. To avoid this warning, enable rendering/viewport/hdr_2d in the Project Settings.");
578 }
579
580 float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
581 scene_root->set_mesh_lod_threshold(mesh_lod_threshold);
582
583 RS::get_singleton()->decals_set_filter(RSE::DecalFilter(int(GLOBAL_GET("rendering/textures/decals/filter"))));
584 RS::get_singleton()->light_projectors_set_filter(RSE::LightProjectorFilter(int(GLOBAL_GET("rendering/textures/light_projectors/filter"))));
585 RS::get_singleton()->lightmaps_set_bicubic_filter(GLOBAL_GET("rendering/lightmapping/lightmap_gi/use_bicubic_filter"));
586 RS::get_singleton()->material_set_use_debanding(GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding"));
587
588 SceneTree *tree = get_tree();
589 tree->set_debug_collisions_color(GLOBAL_GET("debug/shapes/collision/shape_color"));
590 tree->set_debug_collision_contact_color(GLOBAL_GET("debug/shapes/collision/contact_color"));
591
592 if (ProjectSettings::get_singleton()->check_changed_settings_in_group("display/window/hdr/request_hdr_output") || ProjectSettings::get_singleton()->check_changed_settings_in_group("rendering/viewport/hdr_2d")) {
593 const bool use_hdr = GLOBAL_GET("display/window/hdr/request_hdr_output").operator bool() || GLOBAL_GET("rendering/viewport/hdr_2d").operator bool();
594
595 LocalVector<ObjectID> invalid_viewports;
596 for (const ObjectID &id : hdr_viewports) {
597 Viewport *vp = ObjectDB::get_instance<Viewport>(id);
598 if (vp) {
599 vp->set_use_hdr_2d(use_hdr);
600 } else {
601 invalid_viewports.push_back(id);
602 }
603 }
604
605 for (const ObjectID &id : invalid_viewports) {
606 hdr_viewports.erase(id);
607 }
608 }
609
610 ResourceImporterTexture::get_singleton()->update_imports();
611 ResourceImporterStreamedTexture::get_singleton()->update_imports();
612
613 _update_translations();
614
615#ifdef DEBUG_ENABLED
616 NavigationServer2D::get_singleton()->set_debug_navigation_edge_connection_color(GLOBAL_GET("debug/shapes/navigation/2d/edge_connection_color"));
617 NavigationServer2D::get_singleton()->set_debug_navigation_geometry_edge_color(GLOBAL_GET("debug/shapes/navigation/2d/geometry_edge_color"));
618 NavigationServer2D::get_singleton()->set_debug_navigation_geometry_face_color(GLOBAL_GET("debug/shapes/navigation/2d/geometry_face_color"));
619 NavigationServer2D::get_singleton()->set_debug_navigation_geometry_edge_disabled_color(GLOBAL_GET("debug/shapes/navigation/2d/geometry_edge_disabled_color"));
620 NavigationServer2D::get_singleton()->set_debug_navigation_geometry_face_disabled_color(GLOBAL_GET("debug/shapes/navigation/2d/geometry_face_disabled_color"));
621 NavigationServer2D::get_singleton()->set_debug_navigation_enable_edge_connections(GLOBAL_GET("debug/shapes/navigation/2d/enable_edge_connections"));
622 NavigationServer2D::get_singleton()->set_debug_navigation_enable_edge_lines(GLOBAL_GET("debug/shapes/navigation/2d/enable_edge_lines"));
623 NavigationServer2D::get_singleton()->set_debug_navigation_enable_geometry_face_random_color(GLOBAL_GET("debug/shapes/navigation/2d/enable_geometry_face_random_color"));
624
625 NavigationServer3D::get_singleton()->set_debug_navigation_edge_connection_color(GLOBAL_GET("debug/shapes/navigation/3d/edge_connection_color"));
626 NavigationServer3D::get_singleton()->set_debug_navigation_geometry_edge_color(GLOBAL_GET("debug/shapes/navigation/3d/geometry_edge_color"));
627 NavigationServer3D::get_singleton()->set_debug_navigation_geometry_face_color(GLOBAL_GET("debug/shapes/navigation/3d/geometry_face_color"));
628 NavigationServer3D::get_singleton()->set_debug_navigation_geometry_edge_disabled_color(GLOBAL_GET("debug/shapes/navigation/3d/geometry_edge_disabled_color"));
629 NavigationServer3D::get_singleton()->set_debug_navigation_geometry_face_disabled_color(GLOBAL_GET("debug/shapes/navigation/3d/geometry_face_disabled_color"));
630 NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_connections(GLOBAL_GET("debug/shapes/navigation/3d/enable_edge_connections"));
631 NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_connections_xray(GLOBAL_GET("debug/shapes/navigation/3d/enable_edge_connections_xray"));
632 NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_lines(GLOBAL_GET("debug/shapes/navigation/3d/enable_edge_lines"));
633 NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_lines_xray(GLOBAL_GET("debug/shapes/navigation/3d/enable_edge_lines_xray"));
634 NavigationServer3D::get_singleton()->set_debug_navigation_enable_geometry_face_random_color(GLOBAL_GET("debug/shapes/navigation/3d/enable_geometry_face_random_color"));
635#endif // DEBUG_ENABLED
636}
637
638void EditorNode::_gdextensions_reloaded() {
639 // In case the developer is inspecting an object that will be changed by the reload.
640 InspectorDock::get_inspector_singleton()->update_tree();
641
642 // Reload script editor to revalidate GDScript if classes are added or removed.
643 ScriptEditor::get_singleton()->reload_scripts(true);
644
645 // Regenerate documentation without using script documentation cache since that would
646 // revert doc changes during this session.
647 EditorHelp::generate_doc(true, false);
648}
649
650void EditorNode::_update_translations() {
651 Ref<TranslationDomain> main = TranslationServer::get_singleton()->get_main_domain();
652
653 TranslationServer::get_singleton()->load_project_translations(main);
654
655 if (main->is_enabled()) {
656 // Check for the exact locale.
657 if (main->has_translation_for_locale(main->get_locale_override(), true)) {
658 // The set of translation resources for the current locale changed.
659 const HashSet<Ref<Translation>> translations = main->find_translations(main->get_locale_override(), false);
660 if (translations != tracked_translations) {
661 _translation_resources_changed();
662 }
663 } else {
664 // Translations for the current preview locale is removed.
665 main->set_enabled(false);
666 main->set_locale_override(String());
667 _translation_resources_changed();
668 }
669 }
670}
671
672void EditorNode::_translation_resources_changed() {
673 for (const Ref<Translation> &E : tracked_translations) {
674 E->disconnect_changed(callable_mp(this, &EditorNode::_queue_translation_notification));
675 }
676 tracked_translations.clear();
677
678 const Ref<TranslationDomain> main = TranslationServer::get_singleton()->get_main_domain();
679 if (main->is_enabled()) {
680 const HashSet<Ref<Translation>> translations = main->find_translations(main->get_locale_override(), false);
681 tracked_translations.reserve(translations.size());
682 for (const Ref<Translation> &translation : translations) {
683 translation->connect_changed(callable_mp(this, &EditorNode::_queue_translation_notification));
684 tracked_translations.insert(translation);
685 }
686 }
687
688 _queue_translation_notification();
689 emit_signal(SNAME("preview_locale_changed"));
690}
691
692void EditorNode::_queue_translation_notification() {
693 if (pending_translation_notification) {
694 return;
695 }
696 pending_translation_notification = true;
697 callable_mp(this, &EditorNode::_propagate_translation_notification).call_deferred();
698}
699
700void EditorNode::_propagate_translation_notification() {
701 pending_translation_notification = false;
702 scene_root->propagate_notification(NOTIFICATION_TRANSLATION_CHANGED);
703}
704
705void EditorNode::_queue_resource_counter_changed() {
706 if (resource_counter_queued) {
707 return;
708 }
709 callable_mp(this, &EditorNode::_emit_resource_counter_changed).call_deferred();
710 resource_counter_queued = true;
711}
712
713void EditorNode::_emit_resource_counter_changed() {
714 resource_counter_queued = false;
715 emit_signal(SNAME("resource_counter_changed"));
716}
717
718void EditorNode::_update_system_menu_icons(bool p_dark_mode) {
719 file_menu->set_item_icon(file_menu->get_item_index(SCENE_NEW_SCENE), get_editor_theme_native_menu_icon(SNAME("CreateNewSceneFrom"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
720 file_menu->set_item_icon(file_menu->get_item_index(SCENE_OPEN_SCENE), get_editor_theme_native_menu_icon(SNAME("PackedScene"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
721 file_menu->set_item_icon(file_menu->get_item_index(SCENE_SAVE_SCENE), get_editor_theme_native_menu_icon(SNAME("Save"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
722 file_menu->set_item_icon(file_menu->get_item_index(SCENE_QUICK_OPEN), get_editor_theme_native_menu_icon(SNAME("Load"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
723 file_menu->set_item_icon(file_menu->get_item_index(SCENE_UNDO), get_editor_theme_native_menu_icon(SNAME("RotateLeft"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
724 file_menu->set_item_icon(file_menu->get_item_index(SCENE_CLOSE), get_editor_theme_native_menu_icon(SNAME("CloseScene"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
725#ifdef MACOS_ENABLED
726 if (menu_type != MENU_TYPE_GLOBAL) {
727 file_menu->set_item_icon(file_menu->get_item_index(SCENE_QUIT), get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
728 }
729#else
730 file_menu->set_item_icon(file_menu->get_item_index(SCENE_QUIT), get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
731#endif
732
733 project_menu->set_item_icon(project_menu->get_item_index(PROJECT_OPEN_SETTINGS), get_editor_theme_native_menu_icon(SNAME("ClassList"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
734 project_menu->set_item_icon(project_menu->get_item_index(PROJECT_EXPORT), get_editor_theme_native_menu_icon(SNAME("ResourcePreloader"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
735 project_menu->set_item_icon(project_menu->get_item_index(PROJECT_QUIT_TO_PROJECT_MANAGER), get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
736
737#ifdef MACOS_ENABLED
738 if (menu_type != MENU_TYPE_GLOBAL) {
739 settings_menu->set_item_icon(settings_menu->get_item_index(EDITOR_OPEN_SETTINGS), get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
740 } else {
741 apple_menu->set_item_icon(apple_menu->get_item_index(EDITOR_OPEN_SETTINGS), get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
742 }
743#else
744 settings_menu->set_item_icon(settings_menu->get_item_index(EDITOR_OPEN_SETTINGS), get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
745#endif
746
747 help_menu->set_item_icon(help_menu->get_item_index(HELP_SEARCH), get_editor_theme_native_menu_icon(SNAME("HelpSearch"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
748 help_menu->set_item_icon(help_menu->get_item_index(HELP_COPY_SYSTEM_INFO), get_editor_theme_native_menu_icon(SNAME("ActionCopy"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
749#ifdef MACOS_ENABLED
750 if (menu_type != MENU_TYPE_GLOBAL) {
751 help_menu->set_item_icon(help_menu->get_item_index(HELP_ABOUT), get_editor_theme_native_menu_icon(SNAME("Godot"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
752 }
753#else
754 help_menu->set_item_icon(help_menu->get_item_index(HELP_ABOUT), get_editor_theme_native_menu_icon(SNAME("Godot"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
755#endif
756 help_menu->set_item_icon(help_menu->get_item_index(HELP_SUPPORT_GODOT_DEVELOPMENT), get_editor_theme_native_menu_icon(SNAME("Heart"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode));
757}
758
759void EditorNode::_update_theme(bool p_skip_creation) {
760 if (!p_skip_creation) {
761 theme = EditorThemeManager::generate_theme(theme);
762 DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), EditorStringName(Editor)));
763
764#if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
765 if (EditorHelpHighlighter::get_singleton()) {
766 // Update syntax colors.
767 EditorHelpHighlighter::get_singleton()->clear_cache();
768 }
769#endif
770 }
771
772 Vector<Ref<Theme>> editor_themes;
773 editor_themes.push_back(theme);
774 editor_themes.push_back(ThemeDB::get_singleton()->get_default_theme());
775
776 ThemeContext *node_tc = ThemeDB::get_singleton()->get_theme_context(this);
777 if (node_tc) {
778 node_tc->set_themes(editor_themes);
779 } else {
780 ThemeDB::get_singleton()->create_theme_context(this, editor_themes);
781 }
782
783 Window *window = get_window();
784 if (window) {
785 ThemeContext *window_tc = ThemeDB::get_singleton()->get_theme_context(window);
786 if (window_tc) {
787 window_tc->set_themes(editor_themes);
788 } else {
789 ThemeDB::get_singleton()->create_theme_context(window, editor_themes);
790 }
791 }
792
793 if (CanvasItemEditor::get_singleton()->get_theme_preview() == CanvasItemEditor::THEME_PREVIEW_EDITOR) {
794 update_preview_themes(CanvasItemEditor::THEME_PREVIEW_EDITOR);
795 }
796
797 // Update styles.
798 {
799 bool dark_mode = DisplayServer::get_singleton()->is_dark_mode_supported() && DisplayServer::get_singleton()->is_dark_mode();
800
801 gui_base->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("Background"), EditorStringName(EditorStyles)));
802 main_vbox->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT, Control::PRESET_MODE_MINSIZE, theme->get_constant(SNAME("window_border_margin"), EditorStringName(Editor)));
803 main_vbox->add_theme_constant_override("separation", theme->get_constant(SNAME("top_bar_separation"), EditorStringName(Editor)));
804
805 if (main_menu_button != nullptr) {
806 main_menu_button->set_button_icon(theme->get_icon(SNAME("TripleBar"), EditorStringName(EditorIcons)));
807 }
808
809 editor_main_screen->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("Content"), EditorStringName(EditorStyles)));
810 bottom_panel->_theme_changed();
811 distraction_free->set_button_icon(theme->get_icon(SNAME("DistractionFree"), EditorStringName(EditorIcons)));
812 update_distraction_free_button_theme();
813
814 _update_system_menu_icons(dark_mode);
815
816 _update_renderer_color();
817 }
818
819 Ref<Texture2D> thumbnail_icon = gui_base->get_theme_icon(SNAME("file_thumbnail"), SNAME("FileDialog"));
820 default_thumbnail.instantiate();
821 default_thumbnail->set_image(thumbnail_icon->get_image());
822
823 editor_dock_manager->update_tab_styles();
824 editor_dock_manager->update_docks_menu();
825 editor_dock_manager->set_tab_icon_max_width(theme->get_constant(SNAME("class_icon_size"), EditorStringName(Editor)));
826
827#ifdef ANDROID_ENABLED
828 DisplayServer::get_singleton()->window_set_color(theme->get_color(SNAME("background"), EditorStringName(Editor)));
829#endif
830}
831
832Ref<Texture2D> EditorNode::get_editor_theme_native_menu_icon(const StringName &p_name, bool p_global_menu, bool p_dark_mode) const {
833 Ref<Texture2D> tx = theme->get_icon(p_name, SNAME("EditorIcons"));
834 if (!p_global_menu || p_dark_mode == EditorThemeManager::is_dark_icon_and_font()) {
835 return tx;
836 }
837
838 Ref<DPITexture> new_tx = tx;
839 if (new_tx.is_null()) {
840 return tx;
841 }
842 new_tx = new_tx->duplicate();
843
844 Dictionary color_conversion_map;
845 if (!p_dark_mode) {
846 for (KeyValue<Color, Color> &E : EditorColorMap::get_color_conversion_map()) {
847 color_conversion_map[E.key] = E.value;
848 }
849 }
850 new_tx->set_color_map(color_conversion_map);
851
852 return new_tx;
853}
854
855void EditorNode::update_preview_themes(int p_mode) {
856 if (!scene_root->is_inside_tree()) {
857 return; // Too early.
858 }
859
860 Vector<Ref<Theme>> preview_themes;
861
862 switch (p_mode) {
863 case CanvasItemEditor::THEME_PREVIEW_PROJECT:
864 preview_themes.push_back(ThemeDB::get_singleton()->get_project_theme());
865 break;
866
867 case CanvasItemEditor::THEME_PREVIEW_EDITOR:
868 preview_themes.push_back(get_editor_theme());
869 break;
870
871 default:
872 break;
873 }
874
875 preview_themes.push_back(ThemeDB::get_singleton()->get_default_theme());
876
877 ThemeContext *preview_context = ThemeDB::get_singleton()->get_theme_context(scene_root);
878 if (preview_context) {
879 preview_context->set_themes(preview_themes);
880 } else {
881 ThemeDB::get_singleton()->create_theme_context(scene_root, preview_themes);
882 }
883}
884
885bool EditorNode::_is_project_data_missing() {
886 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
887 const String project_data_dir = EditorPaths::get_singleton()->get_project_data_dir();
888 if (!da->dir_exists(project_data_dir)) {
889 return true;
890 }
891
892 String project_data_gdignore_file_path = project_data_dir.path_join(".gdignore");
893 if (!FileAccess::exists(project_data_gdignore_file_path)) {
894 Ref<FileAccess> f = FileAccess::open(project_data_gdignore_file_path, FileAccess::WRITE);
895 if (f.is_valid()) {
896 f->store_line("");
897 } else {
898 ERR_PRINT("Failed to create file " + project_data_gdignore_file_path.quote() + ".");
899 }
900 }
901
902 String uid_cache = ResourceUID::get_singleton()->get_cache_file();
903 if (!da->file_exists(uid_cache)) {
904 Error err = ResourceUID::get_singleton()->save_to_cache();
905 if (err != OK) {
906 ERR_PRINT("Failed to create file " + uid_cache.quote() + ".");
907 }
908 }
909
910 const String dirs[] = {
911 EditorPaths::get_singleton()->get_project_settings_dir(),
912 ProjectSettings::get_singleton()->get_imported_files_path()
913 };
914 for (const String &dir : dirs) {
915 if (!da->dir_exists(dir)) {
916 return true;
917 }
918 }
919 return false;
920}
921
922void EditorNode::_notification(int p_what) {
923 switch (p_what) {
924 case NOTIFICATION_TRANSLATION_CHANGED: {
925 _update_title();
926 callable_mp(this, &EditorNode::_titlebar_resized).call_deferred();
927
928 // The rendering method selector.
929 const String current_renderer_ps = String(GLOBAL_GET("rendering/renderer/rendering_method")).to_lower();
930 const String current_renderer_os = OS::get_singleton()->get_current_rendering_method().to_lower();
931 if (current_renderer_ps == current_renderer_os) {
932 for (int i = 0; i < renderer->get_item_count(); i++) {
933 renderer->set_item_text(i, _to_rendering_method_display_name(renderer->get_item_metadata(i)));
934 }
935 } else {
936 // TRANSLATORS: The placeholder is the rendering method that has overridden the default one.
937 renderer->set_item_text(0, vformat(TTR("%s (Overridden)"), _to_rendering_method_display_name(current_renderer_os)));
938 }
939
940 EditorHelpBit::clear_cache();
941 } break;
942
943 case NOTIFICATION_POSTINITIALIZE: {
944 EditorHelp::generate_doc();
945#if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
946 EditorHelpHighlighter::create_singleton();
947#endif
948 } break;
949
950 case NOTIFICATION_PROCESS: {
951 if (editor_data.is_scene_changed(-1)) {
952 scene_tabs->update_scene_tabs();
953 }
954
955 if (update_spinner->is_visible()) {
956 // Update the animation frame of the update spinner.
957 uint64_t frame = Engine::get_singleton()->get_frames_drawn();
958 uint64_t tick = OS::get_singleton()->get_ticks_msec();
959
960 if (frame != update_spinner_step_frame && (tick - update_spinner_step_msec) > (1000 / 8)) {
961 update_spinner_step++;
962 if (update_spinner_step >= 8) {
963 update_spinner_step = 0;
964 }
965
966 update_spinner_step_msec = tick;
967 update_spinner_step_frame = frame + 1;
968 update_spinner->set_button_icon(theme->get_icon("Progress" + itos(update_spinner_step + 1), EditorStringName(EditorIcons)));
969 }
970 }
971
972 editor_selection->update();
973
974 ResourceImporterTexture::get_singleton()->update_imports();
975 ResourceImporterStreamedTexture::get_singleton()->update_imports();
976
977 if (requested_first_scan) {
978 requested_first_scan = false;
979
980 OS::get_singleton()->benchmark_begin_measure("Editor", "First Scan");
981
982 EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &EditorNode::_execute_upgrades), CONNECT_ONE_SHOT);
983 EditorFileSystem::get_singleton()->scan();
984 }
985
986 if (settings_overrides_changed) {
987 EditorSettings::get_singleton()->notify_changes();
988 EditorSettings::get_singleton()->emit_signal(SNAME("settings_changed"));
989 settings_overrides_changed = false;
990 }
991
992#ifdef ANDROID_ENABLED
993 if (portrait_mode) {
994 const int vk_height = DisplayServer::get_singleton()->virtual_keyboard_get_height();
995 if (vk_height != last_vk_height) {
996 last_vk_height = vk_height;
997 vk_spacer->set_custom_minimum_size(Size2(0, vk_height));
998 }
999 }
1000#endif
1001 } break;
1002
1003 case NOTIFICATION_ENTER_TREE: {
1004 get_tree()->set_disable_node_threading(true); // No node threading while running editor.
1005
1006 Engine::get_singleton()->set_editor_hint(true);
1007
1008 Window *window = get_window();
1009 if (window) {
1010 // Handle macOS fullscreen and extend-to-title changes.
1011 window->connect("titlebar_changed", callable_mp(this, &EditorNode::_titlebar_resized));
1012 }
1013
1014 // Theme has already been created in the constructor, so we can skip that step.
1015 _update_theme(true);
1016
1017 OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/timers/low_processor_mode_sleep_usec")));
1018 get_tree()->get_root()->set_as_audio_listener_3d(false);
1019 get_tree()->get_root()->set_as_audio_listener_2d(false);
1020 get_tree()->get_root()->set_snap_2d_transforms_to_pixel(false);
1021 get_tree()->get_root()->set_snap_2d_vertices_to_pixel(false);
1022 get_tree()->set_auto_accept_quit(false);
1023#ifdef ANDROID_ENABLED
1024 get_tree()->set_quit_on_go_back(false);
1025 bool is_fullscreen = EDITOR_DEF("_is_editor_fullscreen", false);
1026 if (is_fullscreen) {
1027 DisplayServer::get_singleton()->window_set_mode(DisplayServerEnums::WINDOW_MODE_FULLSCREEN);
1028 }
1029 DisplayServer::get_singleton()->connect("orientation_changed", callable_mp(this, &EditorNode::_screen_orientation_changed));
1030#endif
1031 get_tree()->get_root()->connect("files_dropped", callable_mp(this, &EditorNode::_dropped_files));
1032
1033 command_palette->register_shortcuts_as_command();
1034
1035 _begin_first_scan();
1036
1037 last_dark_mode_state = DisplayServer::get_singleton()->is_dark_mode();
1038 last_system_accent_color = DisplayServer::get_singleton()->get_accent_color();
1039 last_system_base_color = DisplayServer::get_singleton()->get_base_color();
1040 DisplayServer::get_singleton()->set_system_theme_change_callback(callable_mp(this, &EditorNode::_check_system_theme_changed));
1041
1042 get_viewport()->connect("size_changed", callable_mp(this, &EditorNode::_viewport_resized));
1043
1044 /* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
1045 } break;
1046
1047 case NOTIFICATION_EXIT_TREE: {
1048 singleton->active_plugins.clear();
1049
1050 if (progress_dialog) {
1051 progress_dialog->queue_free();
1052 }
1053 if (load_error_dialog) {
1054 load_error_dialog->queue_free();
1055 }
1056 if (execute_output_dialog) {
1057 execute_output_dialog->queue_free();
1058 }
1059 if (warning) {
1060 warning->queue_free();
1061 }
1062 if (save_accept) {
1063 save_accept->queue_free();
1064 }
1065 EditorHelp::save_script_doc_cache();
1066 editor_data.save_editor_external_data();
1067 EditorSettings::get_singleton()->save_project_metadata();
1068 FileAccess::set_file_close_fail_notify_callback(nullptr);
1069 log->deinit(); // Do not get messages anymore.
1070 editor_data.clear_edited_scenes();
1071 get_viewport()->disconnect("size_changed", callable_mp(this, &EditorNode::_viewport_resized));
1072 } break;
1073
1074 case NOTIFICATION_READY: {
1075 // Store the default order of bottom docks. It can only be determined dynamically.
1076 PackedStringArray bottom_docks;
1077 bottom_docks.reserve_exact(bottom_panel->get_tab_count());
1078 for (int i = 0; i < bottom_panel->get_tab_count(); i++) {
1079 EditorDock *dock = Object::cast_to<EditorDock>(bottom_panel->get_tab_control(i));
1080 bottom_docks.append(dock->get_effective_layout_key());
1081 }
1082 default_layout->set_value("docks", "dock_9", String(",").join(bottom_docks));
1083
1084 RenderingServer::get_singleton()->viewport_set_disable_2d(get_scene_root()->get_viewport_rid(), true);
1085 RenderingServer::get_singleton()->viewport_set_environment_mode(get_viewport()->get_viewport_rid(), RSE::VIEWPORT_ENVIRONMENT_DISABLED);
1086 DisplayServer::get_singleton()->screen_set_keep_on(EDITOR_GET("interface/editor/display/keep_screen_on"));
1087
1088 feature_profile_manager->notify_changed();
1089
1090 // Save the project after opening to mark it as last modified, except in headless mode.
1091 // Also use this opportunity to ensure default settings are applied to new projects created from the command line
1092 // using `touch project.godot`.
1093 if (!cmdline_mode) {
1094 const String project_settings_path = ProjectSettings::get_singleton()->get_resource_path().path_join("project.godot");
1095 // Check the file's size in bytes as an optimization. If it's under 10 bytes, the file is assumed to be empty.
1096 if (FileAccess::get_size(project_settings_path) < 10) {
1097 const HashMap<String, Variant> initial_settings = get_initial_settings();
1098 for (const KeyValue<String, Variant> &initial_setting : initial_settings) {
1099 ProjectSettings::get_singleton()->set_setting(initial_setting.key, initial_setting.value);
1100 }
1101 }
1102 ProjectSettings::get_singleton()->save();
1103 }
1104
1105 _titlebar_resized();
1106
1107 // Set up a theme context for the 2D preview viewport using the stored preview theme.
1108 CanvasItemEditor::ThemePreviewMode theme_preview_mode = (CanvasItemEditor::ThemePreviewMode)(int)EditorSettings::get_singleton()->get_project_metadata("2d_editor", "theme_preview", CanvasItemEditor::THEME_PREVIEW_PROJECT);
1109 update_preview_themes(theme_preview_mode);
1110
1111 // Remember the selected locale to preview node translations.
1112 const String preview_locale = EditorSettings::get_singleton()->get_project_metadata("editor_metadata", "preview_locale", String());
1113 if (!preview_locale.is_empty() && TranslationServer::get_singleton()->has_translation_for_locale(preview_locale, true)) {
1114 set_preview_locale(preview_locale, false);
1115 }
1116
1117 if (Engine::get_singleton()->is_recovery_mode_hint()) {
1118 EditorToaster::get_singleton()->popup_str(TTR("Recovery Mode is enabled. Editor functionality has been restricted."), EditorToaster::SEVERITY_WARNING);
1119 }
1120
1121 /* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
1122 } break;
1123
1124 case NOTIFICATION_APPLICATION_FOCUS_IN: {
1125 // Restore the original FPS cap after focusing back on the editor.
1126 OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/timers/low_processor_mode_sleep_usec")));
1127
1128 if (_is_project_data_missing()) {
1129 project_data_missing->popup_centered();
1130 } else {
1131 EditorFileSystem::get_singleton()->scan_changes();
1132 }
1133 _scan_external_changes();
1134
1135 GDExtensionManager *gdextension_manager = GDExtensionManager::get_singleton();
1136 callable_mp(gdextension_manager, &GDExtensionManager::reload_extensions).call_deferred();
1137 } break;
1138
1139 case NOTIFICATION_APPLICATION_FOCUS_OUT: {
1140 // Save on focus loss before applying the FPS limit to avoid slowing down the saving process.
1141 if (EDITOR_GET("interface/editor/behavior/save_on_focus_loss")) {
1142 _save_scene_silently();
1143 }
1144
1145 // Set a low FPS cap to decrease CPU/GPU usage while the editor is unfocused.
1146 if (unfocused_low_processor_usage_mode_enabled) {
1147 OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/timers/unfocused_low_processor_mode_sleep_usec")));
1148 }
1149 } break;
1150
1151 case NOTIFICATION_WM_ABOUT: {
1152 show_about();
1153 } break;
1154
1155 case NOTIFICATION_WM_CLOSE_REQUEST: {
1156 _menu_option_confirm(SCENE_QUIT, false);
1157 } break;
1158
1159 case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
1160 if (EditorSettings::get_singleton()->check_changed_settings_in_group("filesystem/file_dialog")) {
1161 FileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files"));
1162 FileDialog::set_default_display_mode(EDITOR_GET("filesystem/file_dialog/display_mode"));
1163 }
1164
1165 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/input/tablet_driver")) {
1166 String tablet_driver = GLOBAL_GET("input_devices/pen_tablet/driver");
1167 int tablet_driver_idx = EDITOR_GET("interface/editor/input/tablet_driver");
1168 if (tablet_driver_idx != -1) {
1169 tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(tablet_driver_idx);
1170 }
1171 if (tablet_driver.is_empty()) {
1172 tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(0);
1173 }
1174 DisplayServer::get_singleton()->tablet_set_current_driver(tablet_driver);
1175 print_verbose("Using \"" + DisplayServer::get_singleton()->tablet_get_current_driver() + "\" pen tablet driver...");
1176 }
1177
1178 if (EDITOR_GET("interface/editor/behavior/import_resources_when_unfocused")) {
1179 scan_changes_timer->start();
1180 } else {
1181 scan_changes_timer->stop();
1182 }
1183
1184 follow_system_theme = EDITOR_GET("interface/theme/follow_system_theme");
1185 use_system_accent_color = EDITOR_GET("interface/theme/use_system_accent_color");
1186
1187 if (EditorThemeManager::is_generated_theme_outdated()) {
1188 class_icon_cache.clear();
1189 _update_theme();
1190 _build_icon_type_cache();
1191 recent_scenes->reset_size();
1192 }
1193
1194 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/timers/dragging_")) {
1195 theme->set_constant("dragging_unfold_wait_msec", "Tree", (float)EDITOR_GET("interface/editor/timers/dragging_hover_wait_seconds") * 1000);
1196 theme->set_constant("hover_switch_wait_msec", "TabBar", (float)EDITOR_GET("interface/editor/timers/dragging_hover_wait_seconds") * 1000);
1197 }
1198
1199 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/docks")) {
1200 editor_dock_manager->update_tab_styles();
1201 }
1202
1203 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/scene_tabs")) {
1204 scene_tabs->update_scene_tabs();
1205 }
1206
1207 if (EditorSettings::get_singleton()->check_changed_settings_in_group("docks/filesystem")) {
1208 HashSet<String> updated_textfile_extensions;
1209 HashSet<String> updated_other_file_extensions;
1210 bool extensions_match = true;
1211 const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
1212 for (const String &E : textfile_ext) {
1213 updated_textfile_extensions.insert(E);
1214 if (extensions_match && !textfile_extensions.has(E)) {
1215 extensions_match = false;
1216 }
1217 }
1218 const Vector<String> other_file_ext = ((String)(EDITOR_GET("docks/filesystem/other_file_extensions"))).split(",", false);
1219 for (const String &E : other_file_ext) {
1220 updated_other_file_extensions.insert(E);
1221 if (extensions_match && !other_file_extensions.has(E)) {
1222 extensions_match = false;
1223 }
1224 }
1225
1226 if (!extensions_match || updated_textfile_extensions.size() < textfile_extensions.size() || updated_other_file_extensions.size() < other_file_extensions.size()) {
1227 textfile_extensions = updated_textfile_extensions;
1228 other_file_extensions = updated_other_file_extensions;
1229 EditorFileSystem::get_singleton()->scan();
1230 }
1231 }
1232
1233 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/appearance")) {
1234 _update_update_spinner();
1235 _update_main_menu_type();
1236 renderer->set_visible(EDITOR_GET("interface/editor/appearance/show_renderer_selector"));
1237 }
1238 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/display")) {
1239 _update_vsync_mode();
1240 DisplayServer::get_singleton()->screen_set_keep_on(EDITOR_GET("interface/editor/display/keep_screen_on"));
1241 }
1242
1243#ifdef ANDROID_ENABLED
1244 if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/touchscreen/touch_actions_panel")) {
1245 _touch_actions_panel_mode_changed();
1246 }
1247#endif
1248 } break;
1249 }
1250}
1251
1252void EditorNode::_update_update_spinner() {
1253 bool should_display_spinner = false;
1254 if (!RenderingServer::get_singleton()->canvas_item_get_debug_redraw()) {
1255#ifdef DEV_ENABLED
1256 const bool in_dev = true;
1257#else
1258 const bool in_dev = false;
1259#endif
1260 const int show_update_spinner_setting = EDITOR_GET("interface/editor/appearance/show_update_spinner");
1261 should_display_spinner = (show_update_spinner_setting == 0 && in_dev) || show_update_spinner_setting == 1;
1262 }
1263 update_spinner->set_visible(should_display_spinner);
1264
1265 const bool update_continuously = EDITOR_GET("interface/editor/display/update_continuously");
1266 OS::get_singleton()->set_low_processor_usage_mode(!update_continuously);
1267
1268 if (!update_spinner->is_visible()) {
1269 return;
1270 }
1271
1272 PopupMenu *update_popup = update_spinner->get_popup();
1273 update_popup->set_item_checked(update_popup->get_item_index(SPINNER_UPDATE_CONTINUOUSLY), update_continuously);
1274 update_popup->set_item_checked(update_popup->get_item_index(SPINNER_UPDATE_WHEN_CHANGED), !update_continuously);
1275
1276 if (update_continuously) {
1277 update_spinner->set_tooltip_text(TTRC("Spins when the editor window redraws.\nUpdate Continuously is enabled, which can increase power usage. Click to disable it."));
1278
1279 // Use a different color for the update spinner when Update Continuously is enabled,
1280 // as this feature should only be enabled for troubleshooting purposes.
1281 // Make the icon modulate color overbright because icons are not completely white on a dark theme.
1282 // On a light theme, icons are dark, so we need to modulate them with an even brighter color.
1283 const bool dark_icon_and_font = EditorThemeManager::is_dark_icon_and_font();
1284 update_spinner->set_self_modulate(theme->get_color(SNAME("error_color"), EditorStringName(Editor)) * (dark_icon_and_font ? Color(1.1, 1.1, 1.1) : Color(4.25, 4.25, 4.25)));
1285 } else {
1286 update_spinner->set_tooltip_text(TTRC("Spins when the editor window redraws."));
1287 update_spinner->set_self_modulate(Color(1, 1, 1));
1288 }
1289}
1290
1291void EditorNode::_execute_upgrades() {
1292 if (run_project_upgrade_tool) {
1293 run_project_upgrade_tool = false;
1294 // Execute another scan to reimport the modified files.
1295 project_upgrade_tool->connect(project_upgrade_tool->UPGRADE_FINISHED, callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::scan), CONNECT_ONE_SHOT);
1296 project_upgrade_tool->finish_upgrade();
1297 }
1298}
1299
1300void EditorNode::init_plugins() {
1301 _initializing_plugins = true;
1302 Vector<String> addons;
1303 if (ProjectSettings::get_singleton()->has_setting("editor_plugins/enabled")) {
1304 addons = GLOBAL_GET("editor_plugins/enabled");
1305 }
1306
1307 for (const String &addon : addons) {
1308 set_addon_plugin_enabled(addon, true);
1309 }
1310 _initializing_plugins = false;
1311
1312 if (!pending_addons.is_empty()) {
1313 EditorFileSystem::get_singleton()->connect("script_classes_updated", callable_mp(this, &EditorNode::_enable_pending_addons), CONNECT_ONE_SHOT);
1314 }
1315}
1316
1317void EditorNode::_on_plugin_ready(Object *p_script, const String &p_activate_name) {
1318 Ref<Script> scr = Object::cast_to<Script>(p_script);
1319 if (scr.is_null()) {
1320 return;
1321 }
1322 project_settings_editor->update_plugins();
1323 project_settings_editor->hide();
1324 push_item(scr.operator->());
1325 if (p_activate_name.length()) {
1326 set_addon_plugin_enabled(p_activate_name, true);
1327 }
1328}
1329
1330void EditorNode::_remove_plugin_from_enabled(const String &p_name) {
1331 ProjectSettings *ps = ProjectSettings::get_singleton();
1332 PackedStringArray enabled_plugins = ps->get("editor_plugins/enabled");
1333 for (int i = 0; i < enabled_plugins.size(); ++i) {
1334 if (enabled_plugins.get(i) == p_name) {
1335 enabled_plugins.remove_at(i);
1336 break;
1337 }
1338 }
1339 ps->set("editor_plugins/enabled", enabled_plugins);
1340}
1341
1342void EditorNode::_plugin_over_edit(EditorPlugin *p_plugin, Object *p_object, bool p_set_current) {
1343 if (p_object) {
1344 editor_plugins_over->add_plugin(p_plugin);
1345 p_plugin->edit(p_object);
1346 p_plugin->make_visible(true);
1347 if (p_set_current) {
1348 p_plugin->set_current();
1349 }
1350 } else {
1351 editor_plugins_over->remove_plugin(p_plugin);
1352 p_plugin->edit(nullptr);
1353 p_plugin->make_visible(false);
1354 }
1355}
1356
1357void EditorNode::_plugin_over_self_own(EditorPlugin *p_plugin) {
1358 active_plugins[p_plugin->get_instance_id()].insert(p_plugin);
1359}
1360
1361void EditorNode::_resources_changed(const Vector<String> &p_resources) {
1362 List<Ref<Resource>> changed;
1363
1364 int rc = p_resources.size();
1365 for (int i = 0; i < rc; i++) {
1366 Ref<Resource> res = ResourceCache::get_ref(p_resources.get(i));
1367 if (res.is_null()) {
1368 continue;
1369 }
1370
1371 if (!res->editor_can_reload_from_file()) {
1372 continue;
1373 }
1374 if (!res->get_path().is_resource_file() && !res->get_path().is_absolute_path()) {
1375 continue;
1376 }
1377 if (!FileAccess::exists(res->get_path())) {
1378 continue;
1379 }
1380
1381 if (!res->get_import_path().is_empty()) {
1382 // This is an imported resource, will be reloaded if reimported via the _resources_reimported() callback.
1383 continue;
1384 }
1385
1386 changed.push_back(res);
1387 }
1388
1389 if (changed.size()) {
1390 for (Ref<Resource> &res : changed) {
1391 res->reload_from_file();
1392 }
1393 }
1394}
1395
1396void EditorNode::_fs_changed() {
1397 for (FileDialog *E : file_dialogs) {
1398 E->invalidate();
1399 }
1400
1401 _mark_unsaved_scenes();
1402
1403 // FIXME: Move this to a cleaner location, it's hacky to do this in _fs_changed.
1404 String export_error;
1405 Error err = OK;
1406 // It's important to wait for the first scan to finish; otherwise, scripts or resources might not be imported.
1407 if (!export_defer.preset.is_empty() && !EditorFileSystem::get_singleton()->is_scanning()) {
1408 String preset_name = export_defer.preset;
1409 // Ensures export_project does not loop infinitely, because notifications may
1410 // come during the export.
1411 export_defer.preset = "";
1412 Ref<EditorExportPreset> export_preset;
1413 for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); ++i) {
1414 export_preset = EditorExport::get_singleton()->get_export_preset(i);
1415 if (export_preset->get_name() == preset_name) {
1416 break;
1417 }
1418 export_preset.unref();
1419 }
1420
1421 if (export_preset.is_null()) {
1422 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1423 if (da->file_exists("res://export_presets.cfg")) {
1424 err = FAILED;
1425 export_error = vformat(
1426 "Invalid export preset name: %s.\nThe following presets were detected in this project's `export_presets.cfg`:\n\n",
1427 preset_name);
1428 for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); ++i) {
1429 // Write the preset name between double quotes since it needs to be written between quotes on the command line if it contains spaces.
1430 export_error += vformat(" \"%s\"\n", EditorExport::get_singleton()->get_export_preset(i)->get_name());
1431 }
1432 } else {
1433 err = FAILED;
1434 export_error = "This project doesn't have an `export_presets.cfg` file at its root.\nCreate an export preset from the \"Project > Export\" dialog and try again.";
1435 }
1436 } else {
1437 Ref<EditorExportPlatform> platform = export_preset->get_platform();
1438 const String export_path = export_defer.path.is_empty() ? export_preset->get_export_path() : export_defer.path;
1439 if (export_path.is_empty()) {
1440 err = FAILED;
1441 export_error = vformat("Export preset \"%s\" doesn't have a default export path, and none was specified.", preset_name);
1442 } else if (platform.is_null()) {
1443 err = FAILED;
1444 export_error = vformat("Export preset \"%s\" doesn't have a matching platform.", preset_name);
1445 } else {
1446 export_preset->update_value_overrides();
1447 if (export_defer.pack_only) { // Only export .pck or .zip data pack.
1448 if (export_path.ends_with(".zip")) {
1449 if (export_defer.patch) {
1450 err = platform->export_zip_patch(export_preset, export_defer.debug, export_path, export_defer.patches);
1451 } else {
1452 err = platform->export_zip(export_preset, export_defer.debug, export_path);
1453 }
1454 } else if (export_path.ends_with(".pck")) {
1455 if (export_defer.patch) {
1456 err = platform->export_pack_patch(export_preset, export_defer.debug, export_path, export_defer.patches);
1457 } else {
1458 err = platform->export_pack(export_preset, export_defer.debug, export_path);
1459 }
1460 } else {
1461 ERR_PRINT(vformat("Export path \"%s\" doesn't end with a supported extension.", export_path));
1462 err = FAILED;
1463 }
1464 } else { // Normal project export.
1465 String config_error;
1466 bool missing_templates;
1467 if (export_defer.android_build_template) {
1468 export_template_manager->install_android_template(export_preset);
1469 }
1470 if (!platform->can_export(export_preset, config_error, missing_templates, export_defer.debug)) {
1471 ERR_PRINT(vformat("Cannot export project with preset \"%s\" due to configuration errors:\n%s", preset_name, config_error));
1472 err = missing_templates ? ERR_FILE_NOT_FOUND : ERR_UNCONFIGURED;
1473 } else {
1474 platform->clear_messages();
1475 err = platform->export_project(export_preset, export_defer.debug, export_path);
1476 }
1477 }
1478 if (err != OK) {
1479 export_error = vformat("Project export for preset \"%s\" failed.", preset_name);
1480 } else if (platform->get_worst_message_type() >= EditorExportPlatform::EXPORT_MESSAGE_WARNING) {
1481 export_error = vformat("Project export for preset \"%s\" completed with warnings.", preset_name);
1482 }
1483 }
1484 }
1485
1486 if (err != OK) {
1487 ERR_PRINT(export_error);
1488 _exit_editor(EXIT_FAILURE);
1489 return;
1490 }
1491 if (!export_error.is_empty()) {
1492 WARN_PRINT(export_error);
1493 }
1494 _exit_editor(EXIT_SUCCESS);
1495 }
1496}
1497
1498void EditorNode::_resources_reimporting(const Vector<String> &p_resources) {
1499 // This will copy all the modified properties of the nodes into 'scenes_modification_table'
1500 // before they are actually reimported. It's important to do this before the reimportation
1501 // because if a mesh is present in an inherited scene, the resource will be modified in
1502 // the inherited scene. Then, get_modified_properties_for_node will return the mesh property,
1503 // which will trigger a recopy of the previous mesh, preventing the reload.
1504 scenes_modification_table.clear();
1505 scenes_reimported.clear();
1506 resources_reimported.clear();
1507 EditorFileSystem *editor_file_system = EditorFileSystem::get_singleton();
1508 for (const String &res_path : p_resources) {
1509 // It's faster to use EditorFileSystem::get_file_type than fetching the resource type from disk.
1510 // This makes a big difference when reimporting many resources.
1511 String file_type = editor_file_system->get_file_type(res_path);
1512 if (file_type.is_empty()) {
1513 file_type = ResourceLoader::get_resource_type(res_path);
1514 }
1515 if (file_type == "PackedScene") {
1516 scenes_reimported.push_back(res_path);
1517 } else {
1518 resources_reimported.push_back(res_path);
1519 }
1520 }
1521
1522 if (scenes_reimported.size() > 0) {
1523 preload_reimporting_with_path_in_edited_scenes(scenes_reimported);
1524 }
1525}
1526
1527void EditorNode::_resources_reimported(const Vector<String> &p_resources) {
1528 int current_tab = scene_tabs->get_current_tab();
1529
1530 for (const String &res_path : resources_reimported) {
1531 if (!ResourceCache::has(res_path)) {
1532 // Not loaded, no need to reload.
1533 continue;
1534 }
1535 // Reload normally.
1536 Ref<Resource> resource = ResourceCache::get_ref(res_path);
1537 if (resource.is_valid()) {
1538 resource->reload_from_file();
1539 }
1540 }
1541
1542 // Editor may crash when related animation is playing while re-importing GLTF scene, stop it in advance.
1543 AnimationPlayer *ap = AnimationPlayerEditor::get_singleton()->get_player();
1544 if (ap && scenes_reimported.size() > 0) {
1545 ap->stop(true);
1546 }
1547
1548 // Only refresh the current scene tab if it's been reimported.
1549 // Otherwise the scene tab will try to grab focus unnecessarily.
1550 bool should_refresh_current_scene_tab = false;
1551 const String current_scene_tab = editor_data.get_scene_path(current_tab);
1552 for (const String &E : scenes_reimported) {
1553 if (!should_refresh_current_scene_tab && E == current_scene_tab) {
1554 should_refresh_current_scene_tab = true;
1555 }
1556 if (editor_data.get_edited_scene_from_path(E) != -1) {
1557 reload_scene(E);
1558 }
1559 }
1560
1561 reload_instances_with_path_in_edited_scenes();
1562
1563 scenes_modification_table.clear();
1564 scenes_reimported.clear();
1565 resources_reimported.clear();
1566
1567 if (should_refresh_current_scene_tab) {
1568 _set_current_scene_nocheck(current_tab);
1569 }
1570}
1571
1572void EditorNode::_sources_changed(bool p_exist) {
1573 if (waiting_for_first_scan) {
1574 waiting_for_first_scan = false;
1575
1576 OS::get_singleton()->benchmark_end_measure("Editor", "First Scan");
1577
1578 for (const String &arg : OS::get_singleton()->get_cmdline_args()) {
1579 if (arg == "--run-upgrade-tool") {
1580 project_upgrade_tool->prepare_upgrade();
1581 return;
1582 }
1583 }
1584
1585 // Reload the global shader variables, but this time
1586 // loading textures, as they are now properly imported.
1587 RenderingServer::get_singleton()->global_shader_parameters_load_settings(true);
1588
1589 _load_editor_layout();
1590
1591 if (!defer_load_scene.is_empty()) {
1592 OS::get_singleton()->benchmark_begin_measure("Editor", "Load Scene");
1593
1594 open_scene(defer_load_scene);
1595 defer_load_scene = "";
1596
1597 OS::get_singleton()->benchmark_end_measure("Editor", "Load Scene");
1598 OS::get_singleton()->benchmark_dump();
1599 }
1600
1601 // Start preview thread now that it's safe.
1602 if (!singleton->cmdline_mode) {
1603 EditorResourcePreview::get_singleton()->start();
1604 }
1605
1606 // Set initial focus for screen reader users.
1607 if (get_tree()->is_accessibility_enabled()) {
1608 if (SceneTreeDock::get_singleton()->is_visible_in_tree()) {
1609 SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->grab_focus();
1610 } else {
1611 TabContainer *tab_container = SceneTreeDock::get_singleton()->get_parent_container();
1612 if (tab_container) {
1613 // Another tab is active (e.g., Import) - focus the tab bar so user can switch.
1614 tab_container->get_tab_bar()->grab_focus();
1615 }
1616 }
1617 }
1618
1619 get_tree()->create_timer(1.0f)->connect("timeout", callable_mp(this, &EditorNode::_remove_lock_file));
1620 }
1621}
1622
1623void EditorNode::_remove_lock_file() {
1624 OS::get_singleton()->remove_lock_file();
1625}
1626
1627void EditorNode::_scan_external_changes() {
1628 disk_changed_list->clear();
1629 TreeItem *r = disk_changed_list->create_item();
1630 disk_changed_list->set_hide_root(true);
1631 bool need_reload = false;
1632
1633 disk_changed_scenes.clear();
1634 disk_changed_project = false;
1635
1636 // Check if any edited scene has changed.
1637 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
1638 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1639
1640 const String scene_path = editor_data.get_scene_path(i);
1641
1642 if (scene_path == "" || !da->file_exists(scene_path)) {
1643 continue;
1644 }
1645
1646 uint64_t last_date = editor_data.get_scene_modified_time(i);
1647 uint64_t date = FileAccess::get_modified_time(scene_path);
1648
1649 if (date > last_date) {
1650 TreeItem *ti = disk_changed_list->create_item(r);
1651 ti->set_text(0, scene_path.get_file());
1652 need_reload = true;
1653 disk_changed_scenes.insert(scene_path);
1654 }
1655 }
1656
1657 String project_settings_path = ProjectSettings::get_singleton()->get_resource_path().path_join("project.godot");
1658 if (FileAccess::get_modified_time(project_settings_path) > ProjectSettings::get_singleton()->get_last_saved_time()) {
1659 TreeItem *ti = disk_changed_list->create_item(r);
1660 ti->set_text(0, "project.godot");
1661 need_reload = true;
1662 disk_changed_project = true;
1663 }
1664
1665 if (need_reload) {
1666 callable_mp((Window *)disk_changed, &Window::popup_centered_ratio).call_deferred(0.3);
1667 }
1668}
1669
1670void EditorNode::_resave_externally_modified_scenes(String p_str) {
1671 save_scene_list(disk_changed_scenes);
1672
1673 if (disk_changed_project) {
1674 ProjectSettings::get_singleton()->save();
1675 }
1676
1677 disk_changed->hide();
1678}
1679
1680void EditorNode::_reload_modified_scenes() {
1681 int current_idx = editor_data.get_edited_scene();
1682
1683 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
1684 if (editor_data.get_scene_path(i) == "") {
1685 continue;
1686 }
1687
1688 uint64_t last_date = editor_data.get_scene_modified_time(i);
1689 uint64_t date = FileAccess::get_modified_time(editor_data.get_scene_path(i));
1690
1691 if (date > last_date) {
1692 String filename = editor_data.get_scene_path(i);
1693 editor_data.set_edited_scene(i);
1694 _remove_edited_scene(false);
1695
1696 Error err = open_scene(filename);
1697 if (err != OK) {
1698 ERR_PRINT(vformat("Failed to load scene: %s", filename));
1699 }
1700 editor_data.move_edited_scene_to_index(i);
1701 }
1702 }
1703
1704 _set_current_scene(current_idx);
1705 scene_tabs->update_scene_tabs();
1706 disk_changed->hide();
1707}
1708
1709void EditorNode::_reload_project_settings() {
1710 ProjectSettings::get_singleton()->setup(ProjectSettings::get_singleton()->get_resource_path(), String(), true, true);
1711}
1712
1713void EditorNode::_vp_resized() {
1714}
1715
1716void EditorNode::_viewport_resized() {
1717 Window *w = get_window();
1718 if (w) {
1719 was_window_windowed_last = w->get_mode() == Window::MODE_WINDOWED;
1720 }
1721}
1722
1723void EditorNode::_titlebar_resized() {
1724 DisplayServer::get_singleton()->window_set_window_buttons_offset(Vector2i(title_bar->get_global_position().y + title_bar->get_size().y / 2, title_bar->get_global_position().y + title_bar->get_size().y / 2), DisplayServerEnums::MAIN_WINDOW_ID);
1725 const Vector3i &margin = DisplayServer::get_singleton()->window_get_safe_title_margins(DisplayServerEnums::MAIN_WINDOW_ID);
1726 if (left_menu_spacer) {
1727 int w = (gui_base->is_layout_rtl()) ? margin.y : margin.x;
1728 left_menu_spacer->set_custom_minimum_size(Size2(w, 0));
1729 }
1730 if (right_menu_spacer) {
1731 int w = (gui_base->is_layout_rtl()) ? margin.x : margin.y;
1732 right_menu_spacer->set_custom_minimum_size(Size2(w, 0));
1733 }
1734 if (title_bar) {
1735 title_bar->set_custom_minimum_size(Size2(0, margin.z - title_bar->get_global_position().y));
1736 }
1737}
1738
1739void EditorNode::_update_undo_redo_allowed() {
1740 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
1741 file_menu->set_item_disabled(file_menu->get_item_index(SCENE_UNDO), !undo_redo->has_undo());
1742 file_menu->set_item_disabled(file_menu->get_item_index(SCENE_REDO), !undo_redo->has_redo());
1743}
1744
1745void EditorNode::_node_renamed() {
1746 if (InspectorDock::get_inspector_singleton()) {
1747 InspectorDock::get_inspector_singleton()->update_tree();
1748 }
1749}
1750
1751void EditorNode::_open_command_palette() {
1752 command_palette->open_popup();
1753}
1754
1755Error EditorNode::load_resource(const String &p_resource, bool p_ignore_broken_deps) {
1756 dependency_errors.clear();
1757
1758 Error err;
1759
1760 Ref<Resource> res;
1761 if (force_textfile_extensions.has(p_resource.get_extension())) {
1762 const String resource_type = ResourceLoader::get_resource_type(p_resource);
1763 if (resource_type != "Translation" && ResourceLoader::exists(p_resource, "")) {
1764 res = ResourceLoader::load(p_resource, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
1765 }
1766 if (res.is_null()) {
1767 res = ResourceCache::get_ref(p_resource);
1768 if (res.is_null() || !res->is_class("TextFile")) {
1769 res = ScriptEditor::get_singleton()->open_file(p_resource);
1770 }
1771 }
1772 } else if (ResourceLoader::exists(p_resource, "")) {
1773 res = ResourceLoader::load(p_resource, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
1774 } else if (textfile_extensions.has(p_resource.get_extension())) {
1775 res = ScriptEditor::get_singleton()->open_file(p_resource);
1776 } else if (other_file_extensions.has(p_resource.get_extension())) {
1777 OS::get_singleton()->shell_open(ProjectSettings::get_singleton()->globalize_path(p_resource));
1778 return OK;
1779 }
1780 ERR_FAIL_COND_V(res.is_null(), ERR_CANT_OPEN);
1781
1782 if (!p_ignore_broken_deps && !dependency_errors.is_empty()) {
1783 dependency_error->show(p_resource, dependency_errors);
1784 dependency_errors.clear();
1785
1786 return ERR_FILE_MISSING_DEPENDENCIES;
1787 }
1788
1789 InspectorDock::get_singleton()->edit_resource(res);
1790 return OK;
1791}
1792
1793Error EditorNode::load_scene_or_resource(const String &p_path, bool p_ignore_broken_deps, bool p_change_scene_tab_if_already_open) {
1794 if (ClassDB::is_parent_class(ResourceLoader::get_resource_type(p_path), "PackedScene")) {
1795 if (!p_change_scene_tab_if_already_open && EditorNode::get_singleton()->is_scene_open(p_path)) {
1796 return OK;
1797 }
1798 return EditorNode::get_singleton()->open_scene(p_path, p_ignore_broken_deps);
1799 }
1800 return EditorNode::get_singleton()->load_resource(p_path, p_ignore_broken_deps);
1801}
1802
1803void EditorNode::edit_node(Node *p_node) {
1804 push_item(p_node);
1805}
1806
1807void EditorNode::edit_resource(const Ref<Resource> &p_resource) {
1808 InspectorDock::get_singleton()->edit_resource(p_resource);
1809}
1810
1811void EditorNode::save_resource_in_path(const Ref<Resource> &p_resource, const String &p_path) {
1812 editor_data.apply_changes_in_editors();
1813
1814 if (saving_resources_in_path.has(p_resource)) {
1815 return;
1816 }
1817 saving_resources_in_path.insert(p_resource);
1818
1819 int flg = 0;
1820 if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
1821 flg |= ResourceSaver::FLAG_COMPRESS;
1822 }
1823
1824 String path = ProjectSettings::get_singleton()->localize_path(p_path);
1825 Error err = ResourceSaver::save(p_resource, path, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
1826
1827 if (err != OK) {
1828 if (ResourceLoader::is_imported(p_resource->get_path())) {
1829 show_warning(vformat(TTR("Cannot save resource at path \"%s\", as it is imported.\nImported resources can't be saved. Instead, modify the source file or change options in the Import dock."), path));
1830 } else {
1831 show_warning(vformat(TTR("Error saving resource at path \"%s\": %s."), path, TTR(error_names[err])));
1832 }
1833
1834 saving_resources_in_path.erase(p_resource);
1835 return;
1836 }
1837
1838 Ref<Resource> prev_resource = ResourceCache::get_ref(p_path);
1839 if (prev_resource.is_null() || prev_resource != p_resource) {
1840 p_resource->set_path(path, true);
1841 }
1842 if (prev_resource.is_valid() && prev_resource != p_resource) {
1843 replace_resources_in_scenes({ prev_resource }, { p_resource });
1844 }
1845 saving_resources_in_path.erase(p_resource);
1846
1847 _resource_saved(p_resource, path);
1848 clear_node_reference(p_resource); // // Check if Resource is saved to disk to potentially remove it from resource_count
1849 emit_signal(SNAME("resource_saved"), p_resource);
1850 editor_data.notify_resource_saved(p_resource);
1851
1852 if (EDITOR_GET("filesystem/on_save/warn_on_saving_large_text_resources")) {
1853 if (p_path.ends_with(".tres")) {
1854 const int64_t file_size = FileAccess::get_size(p_path);
1855 if (file_size >= LARGE_RESOURCE_WARNING_SIZE_THRESHOLD) {
1856 // File is larger than 500 KiB, likely because it contains binary data serialized as Base64.
1857 // This is slow to save and load, so warn the user.
1858 EditorToaster::get_singleton()->popup_str(
1859 vformat(TTR("The text-based resource at path \"%s\" is large on disk (%s), likely because it has embedded binary data.\nThis slows down resource saving and loading.\nConsider saving its binary subresource(s) to a binary `.res` file or saving the resource as a binary `.res` file.\nThis warning can be disabled in the Editor Settings (FileSystem > On Save > Warn on Saving Large Text Resources)."), p_path, String::humanize_size(file_size)), EditorToaster::SEVERITY_WARNING);
1860 }
1861 }
1862 }
1863}
1864
1865void EditorNode::save_resource(const Ref<Resource> &p_resource) {
1866 // If built-in resource, save the scene instead.
1867 if (p_resource->is_built_in()) {
1868 const String scene_path = p_resource->get_path().get_slice("::", 0);
1869 if (!scene_path.is_empty()) {
1870 if (ResourceLoader::exists(scene_path) && ResourceLoader::get_resource_type(scene_path) == "PackedScene") {
1871 save_scene_if_open(scene_path);
1872 } else {
1873 // Not a packed scene, so save it as regular resource.
1874 Ref<Resource> parent_resource = ResourceCache::get_ref(scene_path);
1875 ERR_FAIL_COND_MSG(parent_resource.is_null(), "Parent resource not loaded, can't save.");
1876 save_resource(parent_resource);
1877 }
1878 return;
1879 }
1880 }
1881
1882 // If the resource has been imported, ask the user to use a different path in order to save it.
1883 String path = p_resource->get_path();
1884 if (path.is_resource_file() && !FileAccess::exists(path + ".import")) {
1885 save_resource_in_path(p_resource, p_resource->get_path());
1886 } else {
1887 save_resource_as(p_resource);
1888 }
1889}
1890
1891void EditorNode::save_resource_as(const Ref<Resource> &p_resource, const String &p_at_path) {
1892 String resource_path = p_resource->get_path();
1893 bool is_resource = resource_path.is_resource_file();
1894
1895 {
1896 // Early exit checks.
1897
1898 if (is_resource) {
1899 if (FileAccess::exists(resource_path + ".import")) {
1900 show_warning(TTR("This resource can't be saved because it was imported from another file. Make it unique first."));
1901 return;
1902 }
1903 } else {
1904 int separator_pos = resource_path.find("::");
1905 if (separator_pos != -1) {
1906 String base = resource_path.substr(0, separator_pos);
1907 String base_resource_type = ResourceLoader::get_resource_type(base);
1908 if (base_resource_type == "PackedScene" && (!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base)) {
1909 show_warning(TTR("This resource can't be saved because it does not belong to the edited scene. Make it unique first."));
1910 return;
1911 }
1912 }
1913 }
1914 }
1915
1916 file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
1917 saving_resource = p_resource;
1918
1919 current_menu_option = RESOURCE_SAVE_AS;
1920 List<String> extensions;
1921 ResourceSaver::get_recognized_extensions(p_resource, &extensions);
1922 file->clear_filters();
1923
1924 List<String> preferred;
1925 for (const String &E : extensions) {
1926 if (p_resource->is_class("Script") && (E == "tres" || E == "res")) {
1927 // This serves no purpose and confused people.
1928 continue;
1929 }
1930 file->add_filter("*." + E, E.to_upper());
1931 preferred.push_back(E);
1932 }
1933 // Lowest provided extension priority.
1934 List<String>::Element *res_element = preferred.find("res");
1935 if (res_element) {
1936 preferred.move_to_back(res_element);
1937 }
1938
1939 String resource_name_snake_case = p_resource->get_class().to_snake_case();
1940 String new_resource_name_snake_case;
1941 if (!preferred.is_empty()) {
1942 new_resource_name_snake_case = "new_" + resource_name_snake_case + "." + preferred.front()->get().to_lower();
1943 }
1944
1945 if (!p_at_path.is_empty()) {
1946 file->set_current_dir(p_at_path);
1947 if (is_resource) {
1948 file->set_current_file(resource_path.get_file());
1949 } else {
1950 file->set_current_file(new_resource_name_snake_case);
1951 }
1952 } else if (!p_resource->get_path().get_base_dir().is_empty()) {
1953 if (is_resource) {
1954 if (!extensions.is_empty()) {
1955 const String ext = resource_path.get_extension().to_lower();
1956 if (extensions.find(ext) == nullptr) {
1957 file->set_current_path(resource_path.replacen("." + ext, "." + extensions.front()->get()));
1958 }
1959 }
1960 } else {
1961 file->set_current_file(new_resource_name_snake_case);
1962 }
1963 } else if (!preferred.is_empty()) {
1964 file->set_current_file(new_resource_name_snake_case);
1965 file->set_current_path(new_resource_name_snake_case);
1966 }
1967 file->set_title(TTR("Save Resource As..."));
1968 file->popup_file_dialog();
1969}
1970
1971bool EditorNode::is_resource_internal_to_scene(Ref<Resource> p_resource) {
1972 bool inside_scene = !get_edited_scene() || get_edited_scene()->get_scene_file_path() == p_resource->get_path().get_slice("::", 0);
1973 return inside_scene || p_resource->get_path().is_empty();
1974}
1975
1976void EditorNode::gather_resources(const Variant &p_variant, List<Ref<Resource>> &r_list, HashSet<Object *> &r_scanned_objects, bool p_subresources, bool p_allow_external) {
1977 Variant::Type type = p_variant.get_type();
1978 if (type == Variant::OBJECT && p_variant.get_validated_object() == nullptr) {
1979 return;
1980 }
1981
1982 if (type != Variant::OBJECT && type != Variant::ARRAY && type != Variant::DICTIONARY) {
1983 return;
1984 }
1985
1986 if (type == Variant::ARRAY) {
1987 Array arr = p_variant;
1988 for (const Variant &v : arr) {
1989 Ref<Resource> res = v;
1990 if (res.is_valid()) {
1991 if (p_allow_external) {
1992 r_list.push_back(res);
1993 } else if (is_resource_internal_to_scene(res)) {
1994 r_list.push_back(res);
1995 }
1996 }
1997 if (Object::cast_to<Node>(v) == nullptr) {
1998 gather_resources(v, r_list, r_scanned_objects, p_subresources, p_allow_external);
1999 }
2000 }
2001 return;
2002 }
2003
2004 if (type == Variant::DICTIONARY) {
2005 Dictionary dict = p_variant;
2006 for (const KeyValue<Variant, Variant> &kv : dict) {
2007 Ref<Resource> res_key = kv.key;
2008 Ref<Resource> res_value = kv.value;
2009 if (res_key.is_valid()) {
2010 if (p_allow_external) {
2011 r_list.push_back(res_key);
2012 } else if (is_resource_internal_to_scene(res_key)) {
2013 r_list.push_back(res_key);
2014 }
2015 }
2016 if (res_value.is_valid()) {
2017 if (p_allow_external) {
2018 r_list.push_back(res_value);
2019 } else if (is_resource_internal_to_scene(res_value)) {
2020 r_list.push_back(res_value);
2021 }
2022 }
2023 if (Object::cast_to<Node>(kv.key) == nullptr) {
2024 gather_resources(kv.key, r_list, r_scanned_objects, p_subresources, p_allow_external);
2025 }
2026 if (Object::cast_to<Node>(kv.value) == nullptr) {
2027 gather_resources(kv.value, r_list, r_scanned_objects, p_subresources, p_allow_external);
2028 }
2029 }
2030 return;
2031 }
2032
2033 // Variant::Object
2034
2035 Object *object = p_variant;
2036 if (r_scanned_objects.has(object)) {
2037 return;
2038 }
2039 r_scanned_objects.insert(object);
2040
2041 List<PropertyInfo> pinfo;
2042 object->get_property_list(&pinfo);
2043
2044 for (const PropertyInfo &E : pinfo) {
2045 if (!(E.usage & PROPERTY_USAGE_EDITOR)) {
2046 continue;
2047 }
2048
2049 Variant property_value = object->get(E.name);
2050 Variant::Type property_type = property_value.get_type();
2051 if (property_type == Variant::ARRAY || property_type == Variant::DICTIONARY) {
2052 gather_resources(property_value, r_list, r_scanned_objects, p_subresources, p_allow_external);
2053 continue;
2054 }
2055 Ref<Resource> res = property_value;
2056 if (res.is_null()) {
2057 continue;
2058 }
2059 if (!p_allow_external) {
2060 if (!res->is_built_in() || res->get_path().get_slice("::", 0) != get_edited_scene()->get_scene_file_path()) {
2061 if (!res->get_path().is_empty()) {
2062 continue;
2063 }
2064 }
2065 }
2066 r_list.push_back(res);
2067 if (p_subresources) {
2068 gather_resources(res, r_list, r_scanned_objects, p_subresources, p_allow_external);
2069 }
2070 }
2071}
2072
2073void EditorNode::update_resource_count(Node *p_node, bool p_remove) {
2074 if (!get_edited_scene()) {
2075 return;
2076 }
2077
2078 List<Ref<Resource>> res_list;
2079 HashSet<Object *> scanned_objects;
2080 gather_resources(p_node, res_list, scanned_objects, true);
2081
2082 for (Ref<Resource> &R : res_list) {
2083 List<Node *>::Element *E = resource_count[R].find(p_node);
2084 if (E) {
2085 if (p_remove) {
2086 resource_count[R].erase(E);
2087 }
2088 } else {
2089 resource_count[R].push_back(p_node);
2090 }
2091 }
2092 _queue_resource_counter_changed();
2093}
2094
2095int EditorNode::get_resource_count(Ref<Resource> p_res) {
2096 List<Node *> *L = resource_count.getptr(p_res);
2097 return L ? L->size() : 0;
2098}
2099
2100List<Node *> EditorNode::get_resource_node_list(Ref<Resource> p_res) {
2101 List<Node *> *L = resource_count.getptr(p_res);
2102 return L == nullptr ? List<Node *>() : List<Node *>(*L);
2103}
2104
2105void EditorNode::update_node_reference(const Variant &p_value, Node *p_node, bool p_remove) {
2106 List<Ref<Resource>> list;
2107 Ref<Resource> res = p_value;
2108 HashSet<Object *> scanned_objects;
2109 gather_resources(p_value, list, scanned_objects, true); //Gather all Resources and their SubResources to remove p_node from their lists.
2110
2111 if (res.is_valid() && is_resource_internal_to_scene(res)) {
2112 // Avoid external Resources from being added in.
2113 list.push_back(res);
2114 }
2115
2116 for (Ref<Resource> &R : list) {
2117 if (!p_remove) {
2118 resource_count[R].push_back(p_node);
2119 } else {
2120 List<Node *>::Element *E = resource_count[R].find(p_node);
2121 if (E) {
2122 resource_count[R].erase(E);
2123 }
2124 }
2125 }
2126 _queue_resource_counter_changed();
2127}
2128
2129void EditorNode::clear_node_reference(Ref<Resource> p_res) {
2130 if (is_resource_internal_to_scene(p_res)) {
2131 return;
2132 }
2133 List<Node *> *node_list = resource_count.getptr(p_res);
2134 if (node_list != nullptr) {
2135 node_list->clear();
2136 }
2137}
2138
2139void EditorNode::_menu_option(int p_option) {
2140 _menu_option_confirm(p_option, false);
2141}
2142
2143void EditorNode::_menu_confirm_current() {
2144 _menu_option_confirm(current_menu_option, true);
2145}
2146
2147void EditorNode::trigger_menu_option(int p_option, bool p_confirmed) {
2148 _menu_option_confirm(p_option, p_confirmed);
2149}
2150
2151void EditorNode::_dialog_display_save_error(String p_file, Error p_error) {
2152 if (p_error) {
2153 switch (p_error) {
2154 case ERR_FILE_CANT_WRITE: {
2155 show_warning(TTR("Can't open file for writing:") + " " + p_file.get_extension());
2156 } break;
2157 case ERR_FILE_UNRECOGNIZED: {
2158 show_warning(TTR("Requested file format unknown:") + " " + p_file.get_extension());
2159 } break;
2160 default: {
2161 show_warning(TTR("Error while saving."));
2162 } break;
2163 }
2164 }
2165}
2166
2167void EditorNode::_dialog_display_load_error(String p_file, Error p_error) {
2168 if (p_error) {
2169 switch (p_error) {
2170 case ERR_CANT_OPEN: {
2171 show_warning(vformat(TTR("Can't open file '%s'. The file could have been moved or deleted."), p_file.get_file()));
2172 } break;
2173 case ERR_PARSE_ERROR: {
2174 show_warning(vformat(TTR("Error while parsing file '%s'."), p_file.get_file()));
2175 } break;
2176 case ERR_FILE_CORRUPT: {
2177 show_warning(vformat(TTR("Scene file '%s' appears to be invalid/corrupt."), p_file.get_file()));
2178 } break;
2179 case ERR_FILE_NOT_FOUND: {
2180 show_warning(vformat(TTR("Missing file '%s' or one of its dependencies."), p_file.get_file()));
2181 } break;
2182 case ERR_FILE_UNRECOGNIZED: {
2183 show_warning(vformat(TTR("File '%s' is saved in a format that is newer than the formats supported by this version of Godot, so it can't be opened."), p_file.get_file()));
2184 } break;
2185 default: {
2186 show_warning(vformat(TTR("Error while loading file '%s'."), p_file.get_file()));
2187 } break;
2188 }
2189 }
2190}
2191
2192void EditorNode::_save_editor_states(const String &p_file, int p_idx) {
2193 Node *scene = editor_data.get_edited_scene_root(p_idx);
2194 bool saving_current_scene = p_idx < 0 || editor_data.get_edited_scene() == p_idx;
2195 if (saving_current_scene && !scene) {
2196 return;
2197 }
2198
2199 String path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(p_file.get_file() + "-editstate-" + p_file.md5_text() + ".cfg");
2200
2201 Ref<ConfigFile> cf;
2202 cf.instantiate();
2203
2204 Dictionary md;
2205 if (saving_current_scene) {
2206 md = editor_data.get_editor_plugin_states();
2207
2208 // Save the currently selected nodes.
2209
2210 List<Node *> selection = editor_selection->get_full_selected_node_list();
2211 TypedArray<NodePath> selection_paths;
2212 for (Node *selected_node : selection) {
2213 selection_paths.push_back(scene->get_path_to(selected_node));
2214 }
2215 cf->set_value("editor_states", "$selected_nodes", selection_paths);
2216 } else {
2217 md = editor_data.get_scene_editor_states_with_selection(p_idx);
2218 }
2219
2220 for (const KeyValue<Variant, Variant> &kv : md) {
2221 cf->set_value("editor_states", kv.key, kv.value);
2222 }
2223
2224 Error err = cf->save(path);
2225 ERR_FAIL_COND_MSG(err != OK, "Cannot save config file to '" + path + "'.");
2226}
2227
2228bool EditorNode::_find_and_save_resource(Ref<Resource> p_res, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
2229 if (p_res.is_null()) {
2230 return false;
2231 }
2232
2233 if (processed.has(p_res)) {
2234 return processed[p_res];
2235 }
2236
2237 bool changed = p_res->is_edited();
2238 p_res->set_edited(false);
2239
2240 bool subchanged = _find_and_save_edited_subresources(p_res.ptr(), processed, flags);
2241
2242 if (p_res->get_path().is_resource_file()) {
2243 if (changed || subchanged) {
2244 ResourceSaver::save(p_res, p_res->get_path(), flags);
2245 }
2246 processed[p_res] = false; // Because it's a file.
2247 return false;
2248 } else {
2249 processed[p_res] = changed;
2250 return changed;
2251 }
2252}
2253
2254bool EditorNode::_find_and_save_edited_subresources(Object *obj, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
2255 bool ret_changed = false;
2256 List<PropertyInfo> pi;
2257 obj->get_property_list(&pi);
2258 for (const PropertyInfo &E : pi) {
2259 if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
2260 continue;
2261 }
2262
2263 switch (E.type) {
2264 case Variant::OBJECT: {
2265 Ref<Resource> res = obj->get(E.name);
2266
2267 if (_find_and_save_resource(res, processed, flags)) {
2268 ret_changed = true;
2269 }
2270
2271 } break;
2272 case Variant::ARRAY: {
2273 Array varray = obj->get(E.name);
2274 int len = varray.size();
2275 for (int i = 0; i < len; i++) {
2276 const Variant &v = varray.get(i);
2277 Ref<Resource> res = v;
2278 if (_find_and_save_resource(res, processed, flags)) {
2279 ret_changed = true;
2280 }
2281 }
2282
2283 } break;
2284 case Variant::DICTIONARY: {
2285 Dictionary d = obj->get(E.name);
2286 for (const KeyValue<Variant, Variant> &kv : d) {
2287 Ref<Resource> res = kv.value;
2288 if (_find_and_save_resource(res, processed, flags)) {
2289 ret_changed = true;
2290 }
2291 }
2292 } break;
2293 default: {
2294 }
2295 }
2296 }
2297
2298 return ret_changed;
2299}
2300
2301void EditorNode::_save_edited_subresources(Node *scene, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
2302 _find_and_save_edited_subresources(scene, processed, flags);
2303
2304 for (int i = 0; i < scene->get_child_count(); i++) {
2305 Node *n = scene->get_child(i);
2306 if (n->get_owner() != editor_data.get_edited_scene_root()) {
2307 continue;
2308 }
2309 _save_edited_subresources(n, processed, flags);
2310 }
2311}
2312
2313void EditorNode::_find_node_types(Node *p_node, int &count_2d, int &count_3d) {
2314 if (p_node->is_class("Viewport") || (p_node != editor_data.get_edited_scene_root() && p_node->get_owner() != editor_data.get_edited_scene_root())) {
2315 return;
2316 }
2317
2318 if (p_node->is_class("CanvasItem")) {
2319 count_2d++;
2320 } else if (p_node->is_class("Node3D")) {
2321 count_3d++;
2322 }
2323
2324 for (int i = 0; i < p_node->get_child_count(); i++) {
2325 _find_node_types(p_node->get_child(i), count_2d, count_3d);
2326 }
2327}
2328
2329void EditorNode::_save_scene_with_preview(String p_file, int p_idx) {
2330 save_scene_progress = memnew(EditorProgress("save", TTR("Saving Scene"), 4));
2331
2332 if (editor_data.get_edited_scene_root() != nullptr) {
2333 save_scene_progress->step(TTR("Analyzing"), 0);
2334
2335 int c2d = 0;
2336 int c3d = 0;
2337
2338 _find_node_types(editor_data.get_edited_scene_root(), c2d, c3d);
2339
2340 save_scene_progress->step(TTR("Creating Thumbnail"), 1);
2341 // Current view?
2342
2343 Ref<Image> img;
2344 // If neither 3D or 2D nodes are present, make a 1x1 black texture.
2345 // We cannot fallback on the 2D editor, because it may not have been used yet,
2346 // which would result in an invalid texture.
2347 if (c3d == 0 && c2d == 0) {
2348 img.instantiate();
2349 img->initialize_data(1, 1, false, Image::FORMAT_RGB8);
2350 } else if (c3d < c2d) {
2351 Ref<ViewportTexture> viewport_texture = scene_root->get_texture();
2352 if (viewport_texture->get_width() > 0 && viewport_texture->get_height() > 0) {
2353 img = viewport_texture->get_image();
2354 }
2355 } else {
2356 // The 3D editor may be disabled as a feature, but scenes can still be opened.
2357 // This check prevents the preview from regenerating in case those scenes are then saved.
2358 // The preview will be generated if no feature profile is set (as the 3D editor is enabled by default).
2359 Ref<EditorFeatureProfile> profile = feature_profile_manager->get_current_profile();
2360 if (profile.is_null() || !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D)) {
2361 img = Node3DEditor::get_singleton()->get_editor_viewport(0)->get_viewport_node()->get_texture()->get_image();
2362 }
2363 }
2364
2365 if (img.is_valid() && img->get_width() > 0 && img->get_height() > 0) {
2366 img = img->duplicate();
2367
2368 save_scene_progress->step(TTR("Creating Thumbnail"), 3);
2369
2370 int preview_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
2371 preview_size *= EDSCALE;
2372
2373 // Consider a square region.
2374 int vp_size = MIN(img->get_width(), img->get_height());
2375 int x = (img->get_width() - vp_size) / 2;
2376 int y = (img->get_height() - vp_size) / 2;
2377
2378 if (vp_size < preview_size) {
2379 // Just square it.
2380 img->crop_from_point(x, y, vp_size, vp_size);
2381 } else {
2382 int ratio = vp_size / preview_size;
2383 int size = preview_size * MAX(1, ratio / 2);
2384
2385 x = (img->get_width() - size) / 2;
2386 y = (img->get_height() - size) / 2;
2387
2388 img->crop_from_point(x, y, size, size);
2389 img->resize(preview_size, preview_size, Image::INTERPOLATE_LANCZOS);
2390 }
2391 img->convert(Image::FORMAT_RGB8);
2392
2393 // Save thumbnail directly, as thumbnailer may not update due to actual scene not changing md5.
2394 String temp_path = EditorPaths::get_singleton()->get_cache_dir();
2395 String cache_base = ProjectSettings::get_singleton()->globalize_path(p_file).md5_text();
2396 cache_base = temp_path.path_join("resthumb-" + cache_base);
2397
2398 // Does not have it, try to load a cached thumbnail.
2399 post_process_preview(img);
2400 img->save_png(cache_base + ".png");
2401 }
2402 }
2403
2404 save_scene_progress->step(TTR("Saving Scene"), 4);
2405 _save_scene(p_file, p_idx);
2406
2407 if (!singleton->cmdline_mode) {
2408 EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
2409 }
2410
2411 _close_save_scene_progress();
2412}
2413
2414void EditorNode::_close_save_scene_progress() {
2415 memdelete(save_scene_progress);
2416 save_scene_progress = nullptr;
2417}
2418
2419bool EditorNode::_validate_scene_recursive(const String &p_filename, Node *p_node) {
2420 for (int i = 0; i < p_node->get_child_count(); i++) {
2421 Node *child = p_node->get_child(i);
2422 if (child->get_scene_file_path() == p_filename) {
2423 return true;
2424 }
2425
2426 if (_validate_scene_recursive(p_filename, child)) {
2427 return true;
2428 }
2429 }
2430
2431 return false;
2432}
2433
2434int EditorNode::_save_external_resources(bool p_also_save_external_data) {
2435 // Save external resources and its subresources if any was modified.
2436
2437 int flg = 0;
2438 if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
2439 flg |= ResourceSaver::FLAG_COMPRESS;
2440 }
2441 flg |= ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
2442
2443 HashSet<String> edited_resources;
2444 int saved = 0;
2445 List<Ref<Resource>> cached;
2446 ResourceCache::get_cached_resources(&cached);
2447
2448 for (Ref<Resource> res : cached) {
2449 if (!res->is_edited()) {
2450 continue;
2451 }
2452
2453 String path = res->get_path();
2454 if (path.begins_with("res://")) {
2455 int subres_pos = path.find("::");
2456 if (subres_pos == -1) {
2457 // Actual resource.
2458 edited_resources.insert(path);
2459 } else {
2460 edited_resources.insert(path.substr(0, subres_pos));
2461 }
2462 }
2463
2464 res->set_edited(false);
2465 }
2466
2467 bool script_was_saved = false;
2468 for (const String &E : edited_resources) {
2469 Ref<Resource> res = ResourceCache::get_ref(E);
2470 if (res.is_null()) {
2471 continue; // Maybe it was erased in a thread, who knows.
2472 }
2473 Ref<PackedScene> ps = res;
2474 if (ps.is_valid()) {
2475 continue; // Do not save PackedScenes, this will mess up the editor.
2476 }
2477 if (!script_was_saved) {
2478 Ref<Script> scr = res;
2479 script_was_saved = scr.is_valid();
2480 }
2481 ResourceSaver::save(res, res->get_path(), flg);
2482 saved++;
2483 }
2484
2485 if (script_was_saved) {
2486 ScriptEditor::get_singleton()->update_script_times();
2487 }
2488
2489 if (p_also_save_external_data) {
2490 for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
2491 EditorPlugin *plugin = editor_data.get_editor_plugin(i);
2492 if (!plugin->get_unsaved_status().is_empty()) {
2493 plugin->save_external_data();
2494 saved++;
2495 }
2496 }
2497 }
2498
2499 EditorSettings::get_singleton()->save_project_metadata();
2500 EditorUndoRedoManager::get_singleton()->set_history_as_saved(EditorUndoRedoManager::GLOBAL_HISTORY);
2501 _update_unsaved_cache();
2502
2503 return saved;
2504}
2505
2506void EditorNode::_save_scene_silently() {
2507 // Save scene without displaying progress dialog. Used to work around
2508 // errors about parent node being busy setting up children
2509 // when Save on Focus Loss kicks in.
2510 Node *scene = editor_data.get_edited_scene_root();
2511 if (scene && !scene->get_scene_file_path().is_empty() && FileAccess::exists(scene->get_scene_file_path())) {
2512 _save_scene(scene->get_scene_file_path());
2513 save_editor_layout_delayed();
2514 }
2515}
2516
2517static void _reset_animation_mixers(Node *p_node, List<Pair<AnimationMixer *, Ref<AnimatedValuesBackup>>> *r_anim_backups) {
2518 for (int i = 0; i < p_node->get_child_count(); i++) {
2519 AnimationMixer *mixer = Object::cast_to<AnimationMixer>(p_node->get_child(i));
2520 if (mixer && mixer->is_active() && mixer->is_reset_on_save_enabled() && mixer->can_apply_reset()) {
2521 AnimationTree *tree = Object::cast_to<AnimationTree>(p_node->get_child(i));
2522 if (tree) {
2523 AnimationPlayer *player = Object::cast_to<AnimationPlayer>(tree->get_node_or_null(tree->get_animation_player()));
2524 if (player && player->is_active() && player->is_reset_on_save_enabled() && player->can_apply_reset()) {
2525 continue; // Avoid to process reset/restore many times.
2526 }
2527 }
2528 Ref<AnimatedValuesBackup> backup = mixer->apply_reset();
2529 if (backup.is_valid()) {
2530 Pair<AnimationMixer *, Ref<AnimatedValuesBackup>> pair;
2531 pair.first = mixer;
2532 pair.second = backup;
2533 r_anim_backups->push_back(pair);
2534 }
2535 }
2536 _reset_animation_mixers(p_node->get_child(i), r_anim_backups);
2537 }
2538}
2539
2540void EditorNode::_save_scene(String p_file, int idx) {
2541 ERR_FAIL_COND_MSG(!saving_scene.is_empty() && saving_scene == p_file, "Scene saved while already being saved!");
2542
2543 Node *scene = editor_data.get_edited_scene_root(idx);
2544
2545 if (!scene) {
2546 show_warning(TTR("This operation can't be done without a tree root."));
2547 return;
2548 }
2549
2550 if (!scene->get_scene_file_path().is_empty() && _validate_scene_recursive(scene->get_scene_file_path(), scene)) {
2551 show_warning(TTR("This scene can't be saved because there is a cyclic instance inclusion.\nPlease resolve it and then attempt to save again."));
2552 return;
2553 }
2554
2555 scene->propagate_notification(NOTIFICATION_EDITOR_PRE_SAVE);
2556
2557 editor_data.apply_changes_in_editors();
2558 save_default_environment();
2559 List<Pair<AnimationMixer *, Ref<AnimatedValuesBackup>>> anim_backups;
2560 _reset_animation_mixers(scene, &anim_backups);
2561 _save_editor_states(p_file, idx);
2562
2563 Ref<PackedScene> sdata;
2564
2565 if (ResourceCache::has(p_file)) {
2566 // Something may be referencing this resource and we are good with that.
2567 // We must update it, but also let the previous scene state go, as
2568 // old version still work for referencing changes in instantiated or inherited scenes.
2569
2570 sdata = ResourceCache::get_ref(p_file);
2571 if (sdata.is_valid()) {
2572 sdata->recreate_state();
2573 } else {
2574 sdata.instantiate();
2575 }
2576 } else {
2577 sdata.instantiate();
2578 }
2579 Error err = sdata->pack(scene);
2580
2581 if (err != OK) {
2582 show_warning(TTR("Couldn't save scene. Likely dependencies (instances or inheritance) couldn't be satisfied."));
2583 return;
2584 }
2585
2586 int flg = 0;
2587 if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
2588 flg |= ResourceSaver::FLAG_COMPRESS;
2589 }
2590 flg |= ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
2591
2592 err = ResourceSaver::save(sdata, p_file, flg);
2593
2594 // This needs to be emitted before saving external resources.
2595 emit_signal(SNAME("scene_saved"), p_file);
2596 editor_data.notify_scene_saved(p_file);
2597
2598 _save_external_resources();
2599 saving_scene = p_file; // Some editors may save scenes of built-in resources as external data, so avoid saving this scene again.
2600 editor_data.save_editor_external_data();
2601 saving_scene = "";
2602
2603 for (Pair<AnimationMixer *, Ref<AnimatedValuesBackup>> &E : anim_backups) {
2604 E.first->restore(E.second);
2605 }
2606
2607 if (err == OK) {
2608 scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_file));
2609 editor_data.set_scene_as_saved(idx);
2610 editor_data.set_scene_modified_time(idx, FileAccess::get_modified_time(p_file));
2611
2612 if (EDITOR_GET("filesystem/on_save/warn_on_saving_large_text_resources")) {
2613 if (p_file.ends_with(".tscn") || p_file.ends_with(".tres")) {
2614 const int64_t file_size = FileAccess::get_size(p_file);
2615 if (file_size >= LARGE_RESOURCE_WARNING_SIZE_THRESHOLD) {
2616 // File is larger than 500 KiB, likely because it contains binary data serialized as Base64.
2617 // This is slow to save and load, so warn the user.
2618 EditorToaster::get_singleton()->popup_str(
2619 vformat(TTR("The text-based scene at path \"%s\" is large on disk (%s), likely because it has embedded binary data.\nThis slows down scene saving and loading.\nConsider saving its binary subresource(s) to a binary `.res` file or saving the scene as a binary `.scn` file.\nThis warning can be disabled in the Editor Settings (FileSystem > On Save > Warn on Saving Large Text Resources)."), p_file, String::humanize_size(file_size)), EditorToaster::SEVERITY_WARNING);
2620 }
2621 }
2622 }
2623
2624 editor_folding.save_scene_folding(scene, p_file);
2625
2626 _update_title();
2627 scene_tabs->update_scene_tabs();
2628 } else {
2629 _dialog_display_save_error(p_file, err);
2630 }
2631
2632 scene->propagate_notification(NOTIFICATION_EDITOR_POST_SAVE);
2633 _update_unsaved_cache();
2634}
2635
2636void EditorNode::save_all_scenes() {
2637 project_run_bar->stop_playing();
2638 _save_all_scenes();
2639}
2640
2641void EditorNode::save_scene_if_open(const String &p_scene_path) {
2642 int idx = editor_data.get_edited_scene_from_path(p_scene_path);
2643 if (idx >= 0) {
2644 _save_scene(p_scene_path, idx);
2645 }
2646}
2647
2648void EditorNode::save_scene_list(const HashSet<String> &p_scene_paths) {
2649 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
2650 Node *scene = editor_data.get_edited_scene_root(i);
2651
2652 if (scene && p_scene_paths.has(scene->get_scene_file_path())) {
2653 _save_scene(scene->get_scene_file_path(), i);
2654 }
2655 }
2656}
2657
2658void EditorNode::save_before_run() {
2659 current_menu_option = SAVE_AND_RUN;
2660 _menu_option_confirm(SCENE_SAVE_AS_SCENE, true);
2661 file->set_title(TTR("Save scene before running..."));
2662}
2663
2664void EditorNode::try_autosave() {
2665 if (!bool(EDITOR_GET("run/auto_save/save_before_running"))) {
2666 return;
2667 }
2668
2669 if (unsaved_cache) {
2670 Node *scene = editor_data.get_edited_scene_root();
2671
2672 if (scene && !scene->get_scene_file_path().is_empty()) { // Only autosave if there is a scene and if it has a path.
2673 _save_scene_with_preview(scene->get_scene_file_path());
2674 }
2675 }
2676 _menu_option(SCENE_SAVE_ALL_SCENES);
2677 editor_data.save_editor_external_data();
2678}
2679
2680void EditorNode::restart_editor(bool p_goto_project_manager) {
2681 _menu_option_confirm(p_goto_project_manager ? PROJECT_QUIT_TO_PROJECT_MANAGER : PROJECT_RELOAD_CURRENT_PROJECT, false);
2682}
2683
2684void EditorNode::_save_all_scenes() {
2685 scenes_to_save_as.clear(); // In case saving was canceled before.
2686 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
2687 if (!is_scene_unsaved(i)) {
2688 continue;
2689 }
2690
2691 const Node *scene = editor_data.get_edited_scene_root(i);
2692 ERR_FAIL_NULL(scene);
2693
2694 const String &scene_path = scene->get_scene_file_path();
2695 if (scene_path.is_empty() || !DirAccess::exists(scene_path.get_base_dir())) {
2696 scenes_to_save_as.push_back(i);
2697 continue;
2698 }
2699
2700 if (i == editor_data.get_edited_scene()) {
2701 _save_scene_with_preview(scene_path);
2702 } else {
2703 _save_scene(scene_path, i);
2704 }
2705 }
2706 save_default_environment();
2707
2708 if (!scenes_to_save_as.is_empty()) {
2709 _proceed_save_asing_scene_tabs();
2710 }
2711}
2712
2713void EditorNode::_mark_unsaved_scenes() {
2714 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
2715 Node *node = editor_data.get_edited_scene_root(i);
2716 if (!node) {
2717 continue;
2718 }
2719
2720 String path = node->get_scene_file_path();
2721 if (!path.is_empty() && !FileAccess::exists(path)) {
2722 // Mark scene tab as unsaved if the file is gone.
2723 EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(editor_data.get_scene_history_id(i));
2724 }
2725 }
2726
2727 _update_title();
2728 scene_tabs->update_scene_tabs();
2729}
2730
2731bool EditorNode::is_scene_unsaved(int p_idx) {
2732 const Node *scene = editor_data.get_edited_scene_root(p_idx);
2733 if (!scene) {
2734 return false;
2735 }
2736
2737 if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(p_idx))) {
2738 return true;
2739 }
2740
2741 const String &scene_path = scene->get_scene_file_path();
2742 if (!scene_path.is_empty()) {
2743 // Check if scene has unsaved changes in built-in resources.
2744 for (int j = 0; j < editor_data.get_editor_plugin_count(); j++) {
2745 if (!editor_data.get_editor_plugin(j)->get_unsaved_status(scene_path).is_empty()) {
2746 return true;
2747 }
2748 }
2749 }
2750 return false;
2751}
2752
2753void EditorNode::_dialog_action(String p_file) {
2754 switch (current_menu_option) {
2755 case SCENE_NEW_INHERITED_SCENE: {
2756 Node *scene = editor_data.get_edited_scene_root();
2757 // If the previous scene is rootless, just close it in favor of the new one.
2758 if (!scene) {
2759 _menu_option_confirm(SCENE_CLOSE, true);
2760 }
2761
2762 open_scene(p_file, false, true);
2763 } break;
2764 case SCENE_OPEN_SCENE: {
2765 open_scene(p_file);
2766 } break;
2767 case SETTINGS_PICK_MAIN_SCENE: {
2768 ProjectSettings::get_singleton()->set("application/run/main_scene", ResourceUID::path_to_uid(p_file));
2769 ProjectSettings::get_singleton()->save();
2770 // TODO: Would be nice to show the project manager opened with the highlighted field.
2771
2772 project_run_bar->play_main_scene((bool)pick_main_scene->get_meta("from_native", false));
2773 } break;
2774 case SCENE_CLOSE:
2775 case SCENE_TAB_CLOSE:
2776 case SCENE_SAVE_SCENE:
2777 case SCENE_MULTI_SAVE_AS_SCENE:
2778 case SCENE_SAVE_AS_SCENE:
2779 case SCENE_TAB_SAVE_SCENE:
2780 case SCENE_TAB_SAVE_AS_MAIN_SCENE:
2781 case SCENE_TAB_SAVE_AS_AND_RUN: {
2782 int scene_idx = -1;
2783 if (current_menu_option == SCENE_CLOSE || current_menu_option == SCENE_TAB_CLOSE) {
2784 scene_idx = tab_closing_idx;
2785 } else if (current_menu_option == SCENE_TAB_SAVE_SCENE || current_menu_option == SCENE_TAB_SAVE_AS_MAIN_SCENE || current_menu_option == SCENE_TAB_SAVE_AS_AND_RUN) {
2786 scene_idx = scene_tabs->get_option_tab();
2787 }
2788
2789 if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
2790 bool same_open_scene = false;
2791 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
2792 if (editor_data.get_scene_path(i) == p_file && i != scene_idx) {
2793 same_open_scene = true;
2794 }
2795 }
2796
2797 if (same_open_scene) {
2798 show_warning(TTR("Can't overwrite scene that is still open!"));
2799 return;
2800 }
2801
2802 save_default_environment();
2803 _save_scene_with_preview(p_file, scene_idx);
2804 _add_to_recent_scenes(p_file);
2805 save_editor_layout_delayed();
2806
2807 if (scene_idx != -1) {
2808 _discard_changes();
2809 } else {
2810 // Update the path of the edited scene to ensure later do/undo action history matches.
2811 editor_data.set_scene_path(editor_data.get_edited_scene(), p_file);
2812 }
2813 }
2814
2815 if (current_menu_option == SCENE_MULTI_SAVE_AS_SCENE) {
2816 _proceed_save_asing_scene_tabs();
2817 } else if (current_menu_option == SCENE_TAB_SAVE_AS_MAIN_SCENE) {
2818 _menu_option_confirm(EditorSceneTabs::SCENE_SET_AS_MAIN_SCENE, true);
2819 } else if (current_menu_option == SCENE_TAB_SAVE_AS_AND_RUN) {
2820 project_run_bar->play_custom_scene(p_file);
2821 }
2822 } break;
2823
2824 case SAVE_AND_RUN: {
2825 if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
2826 save_default_environment();
2827 _save_scene_with_preview(p_file);
2828 project_run_bar->play_custom_scene(p_file);
2829 }
2830 } break;
2831
2832 case SAVE_AND_RUN_MAIN_SCENE: {
2833 ProjectSettings::get_singleton()->set("application/run/main_scene", ResourceUID::path_to_uid(p_file));
2834 ProjectSettings::get_singleton()->save();
2835
2836 if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
2837 save_default_environment();
2838 _save_scene_with_preview(p_file);
2839 project_run_bar->play_main_scene((bool)pick_main_scene->get_meta("from_native", false));
2840 }
2841 } break;
2842
2843 case FILE_EXPORT_MESH_LIBRARY: {
2844 const Dictionary &fd_options = file_export_lib->get_selected_options();
2845 bool merge_with_existing_library = fd_options.get(TTR("Merge With Existing"), true);
2846 bool apply_mesh_instance_transforms = fd_options.get(TTR("Apply MeshInstance Transforms"), false);
2847
2848 Ref<MeshLibrary> ml;
2849 if (merge_with_existing_library && FileAccess::exists(p_file)) {
2850 ml = ResourceLoader::load(p_file, "MeshLibrary");
2851
2852 if (ml.is_null()) {
2853 show_warning(TTR("Can't load MeshLibrary for merging!"));
2854 return;
2855 }
2856 }
2857
2858 if (ml.is_null()) {
2859 ml.instantiate();
2860 }
2861
2862 MeshLibraryEditor::update_library_file(editor_data.get_edited_scene_root(), ml, merge_with_existing_library, apply_mesh_instance_transforms);
2863
2864 Error err = ResourceSaver::save(ml, p_file);
2865 if (err) {
2866 show_warning(TTR("Error saving MeshLibrary!"));
2867 return;
2868 } else if (ResourceCache::has(p_file)) {
2869 // Make sure MeshLibrary is updated in the editor.
2870 ResourceLoader::load(p_file)->reload_from_file();
2871 }
2872
2873 } break;
2874
2875 case PROJECT_PACK_AS_ZIP: {
2876 ProjectZIPPacker::pack_project_zip(p_file);
2877 {
2878 Ref<FileAccess> f = FileAccess::open(p_file, FileAccess::READ);
2879 ERR_FAIL_COND_MSG(f.is_null(), vformat("Unable to create ZIP file at: %s. Check for write permissions and whether you have enough disk space left.", p_file));
2880 }
2881
2882 } break;
2883
2884 case RESOURCE_SAVE:
2885 case RESOURCE_SAVE_AS: {
2886 ERR_FAIL_COND(saving_resource.is_null());
2887 save_resource_in_path(saving_resource, p_file);
2888
2889 saving_resource = Ref<Resource>();
2890 ObjectID current_id = editor_history.get_current();
2891 Object *current_obj = current_id.is_valid() ? ObjectDB::get_instance(current_id) : nullptr;
2892 ERR_FAIL_NULL(current_obj);
2893 InspectorDock::get_inspector_singleton()->update_properties_recursive();
2894 } break;
2895 case LAYOUT_SAVE: {
2896 if (p_file.is_empty()) {
2897 return;
2898 }
2899
2900 Ref<ConfigFile> config;
2901 config.instantiate();
2902 Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
2903
2904 if (err == ERR_FILE_CANT_OPEN || err == ERR_FILE_NOT_FOUND) {
2905 config.instantiate();
2906 } else if (err != OK) {
2907 show_warning(TTR("An error occurred while trying to save the editor layout.\nMake sure the editor's user data path is writable."));
2908 return;
2909 }
2910
2911 editor_dock_manager->save_docks_to_config(config, p_file);
2912
2913 config->save(EditorSettings::get_singleton()->get_editor_layouts_config());
2914
2915 layout_dialog->hide();
2916 _update_layouts_menu();
2917
2918 if (p_file == "Default") {
2919 show_warning(TTR("Default editor layout overridden.\nTo restore the Default layout to its base settings, use the Delete Layout option and delete the Default layout."));
2920 }
2921
2922 } break;
2923 case LAYOUT_DELETE: {
2924 Ref<ConfigFile> config;
2925 config.instantiate();
2926
2927 Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
2928 if (err != OK || !config->has_section(p_file)) {
2929 show_warning(TTR("Layout name not found!"));
2930 return;
2931 }
2932
2933 for (const String &section : config->get_sections()) {
2934 // Erase sections related to the layout.
2935 if (section == p_file || section.begins_with(p_file + "/")) {
2936 config->erase_section(section);
2937 }
2938 }
2939
2940 config->save(EditorSettings::get_singleton()->get_editor_layouts_config());
2941
2942 layout_dialog->hide();
2943 _update_layouts_menu();
2944
2945 if (p_file == "Default") {
2946 show_warning(TTR("Restored the Default layout to its base settings."));
2947 }
2948
2949 } break;
2950 default: {
2951 // Save scene?
2952 if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
2953 _save_scene_with_preview(p_file);
2954 }
2955
2956 } break;
2957 }
2958}
2959
2960bool EditorNode::_is_class_editor_disabled_by_feature_profile(const StringName &p_class) {
2961 Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
2962 if (profile.is_null()) {
2963 return false;
2964 }
2965
2966 StringName class_name = p_class;
2967
2968 while (class_name != StringName()) {
2969 if (profile->is_class_disabled(class_name)) {
2970 return true;
2971 }
2972 if (profile->is_class_editor_disabled(class_name)) {
2973 return true;
2974 }
2975 class_name = ClassDB::get_parent_class(class_name);
2976 }
2977
2978 return false;
2979}
2980
2981void EditorNode::edit_item(Object *p_object, Object *p_editing_owner, bool p_set_current) {
2982 ERR_FAIL_NULL(p_editing_owner);
2983
2984 // Editing for this type of object may be disabled by user's feature profile.
2985 if (!p_object || _is_class_editor_disabled_by_feature_profile(p_object->get_class())) {
2986 // Nothing to edit, clean up the owner context and return.
2987 hide_unused_editors(p_editing_owner);
2988 return;
2989 }
2990
2991 // Get a list of editor plugins that can handle this type of object.
2992 Vector<EditorPlugin *> available_plugins = editor_data.get_handling_sub_editors(p_object);
2993 if (available_plugins.is_empty()) {
2994 // None, clean up the owner context and return.
2995 hide_unused_editors(p_editing_owner);
2996 return;
2997 }
2998
2999 ObjectID owner_id = p_editing_owner->get_instance_id();
3000
3001 // Remove editor plugins no longer used by this editing owner. Keep the ones that can
3002 // still be reused by the new edited object.
3003
3004 List<EditorPlugin *> to_remove;
3005 for (EditorPlugin *plugin : active_plugins[owner_id]) {
3006 if (!available_plugins.has(plugin)) {
3007 to_remove.push_back(plugin);
3008 if (plugin->can_auto_hide()) {
3009 _plugin_over_edit(plugin, nullptr);
3010 } else {
3011 // If plugin can't be hidden, make it own itself and become responsible for closing.
3012 _plugin_over_self_own(plugin);
3013 }
3014 }
3015 }
3016
3017 for (EditorPlugin *plugin : to_remove) {
3018 active_plugins[owner_id].erase(plugin);
3019 }
3020
3021 LocalVector<EditorPlugin *> to_over_edit;
3022
3023 // Send the edited object to the plugins.
3024 for (EditorPlugin *plugin : available_plugins) {
3025 if (active_plugins[owner_id].has(plugin)) {
3026 // Plugin was already active, just change the object and ensure it's visible.
3027 plugin->edit(p_object);
3028 plugin->make_visible(true);
3029 if (p_set_current) {
3030 plugin->set_current();
3031 }
3032 continue;
3033 }
3034
3035 if (active_plugins.has(plugin->get_instance_id())) {
3036 // Plugin is already active, but as self-owning, so it needs a separate check.
3037 plugin->edit(p_object);
3038 plugin->make_visible(true);
3039 if (p_set_current) {
3040 plugin->set_current();
3041 }
3042 continue;
3043 }
3044
3045 bool need_to_add = true;
3046 List<EditorPropertyResource *> to_fold;
3047
3048 // If plugin is already associated with another owner, remove it from there first.
3049 for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) {
3050 if (kv.key == owner_id || !kv.value.has(plugin)) {
3051 continue;
3052 }
3053 EditorPropertyResource *epres = ObjectDB::get_instance<EditorPropertyResource>(kv.key);
3054 if (epres) {
3055 // If it's resource property editing the same resource type, fold it later to avoid premature modifications
3056 // that may result in unsafe iteration of active_plugins.
3057 to_fold.push_back(epres);
3058 } else {
3059 kv.value.erase(plugin);
3060 need_to_add = false;
3061 }
3062 }
3063
3064 if (!need_to_add && to_fold.is_empty()) {
3065 plugin->edit(p_object);
3066 plugin->make_visible(true);
3067 } else {
3068 for (EditorPropertyResource *epres : to_fold) {
3069 epres->fold_resource();
3070 }
3071
3072 // TODO: Call the function directly once a proper priority system is implemented.
3073 to_over_edit.push_back(plugin);
3074 }
3075
3076 // Activate previously inactive plugin and edit the object.
3077 active_plugins[owner_id].insert(plugin);
3078 }
3079
3080 for (EditorPlugin *plugin : to_over_edit) {
3081 _plugin_over_edit(plugin, p_object, p_set_current);
3082 }
3083}
3084
3085void EditorNode::push_node_item(Node *p_node) {
3086 if (p_node || !InspectorDock::get_inspector_singleton()->get_edited_object() || Object::cast_to<Node>(InspectorDock::get_inspector_singleton()->get_edited_object()) || Object::cast_to<MultiNodeEdit>(InspectorDock::get_inspector_singleton()->get_edited_object())) {
3087 // Don't push null if the currently edited object is not a Node.
3088 push_item(p_node);
3089 }
3090}
3091
3092void EditorNode::push_item(Object *p_object, const String &p_property, bool p_inspector_only) {
3093 if (!p_object) {
3094 InspectorDock::get_inspector_singleton()->edit(nullptr);
3095 SignalsDock::get_singleton()->set_object(nullptr);
3096 GroupsDock::get_singleton()->set_selection(Vector<Node *>());
3097 SceneTreeDock::get_singleton()->set_selected(nullptr);
3098 InspectorDock::get_singleton()->update(nullptr);
3099 EditorDebuggerNode::get_singleton()->clear_remote_tree_selection();
3100 hide_unused_editors();
3101 return;
3102 }
3103 _add_to_history(p_object, p_property, p_inspector_only);
3104 _edit_current();
3105}
3106
3107void EditorNode::edit_previous_item() {
3108 if (editor_history.previous()) {
3109 _edit_current();
3110 }
3111}
3112
3113void EditorNode::push_item_no_inspector(Object *p_object) {
3114 _add_to_history(p_object, "", false);
3115 _edit_current(false, true);
3116}
3117
3118void EditorNode::save_default_environment() {
3119 Ref<Environment> fallback = get_tree()->get_root()->get_world_3d()->get_fallback_environment();
3120
3121 if (fallback.is_valid() && fallback->get_path().is_resource_file()) {
3122 HashMap<Ref<Resource>, bool> processed;
3123 _find_and_save_edited_subresources(fallback.ptr(), processed, 0);
3124 save_resource_in_path(fallback, fallback->get_path());
3125 }
3126}
3127
3128void EditorNode::hide_unused_editors(const Object *p_editing_owner) {
3129 if (p_editing_owner) {
3130 const ObjectID id = p_editing_owner->get_instance_id();
3131 for (EditorPlugin *plugin : active_plugins[id]) {
3132 if (plugin->can_auto_hide()) {
3133 _plugin_over_edit(plugin, nullptr);
3134 } else {
3135 _plugin_over_self_own(plugin);
3136 }
3137 }
3138 active_plugins.erase(id);
3139 } else {
3140 // If no editing owner is provided, this method will go over all owners and check if they are valid.
3141 // This is to sweep properties that were removed from the inspector.
3142 List<ObjectID> to_remove;
3143 for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) {
3144 Object *context = ObjectDB::get_instance(kv.key);
3145 if (context) {
3146 // In case of self-owning plugins, they are disabled here if they can auto hide.
3147 const EditorPlugin *self_owning = Object::cast_to<EditorPlugin>(context);
3148 if (self_owning && self_owning->can_auto_hide()) {
3149 context = nullptr;
3150 }
3151 }
3152
3153 if (!context || context->call(SNAME("_should_stop_editing"))) {
3154 to_remove.push_back(kv.key);
3155 for (EditorPlugin *plugin : kv.value) {
3156 if (plugin->can_auto_hide()) {
3157 _plugin_over_edit(plugin, nullptr);
3158 } else {
3159 _plugin_over_self_own(plugin);
3160 }
3161 }
3162 }
3163 }
3164
3165 for (const ObjectID &id : to_remove) {
3166 active_plugins.erase(id);
3167 }
3168 }
3169}
3170
3171void EditorNode::_add_to_history(const Object *p_object, const String &p_property, bool p_inspector_only) {
3172 ObjectID id = p_object->get_instance_id();
3173 ObjectID history_id = editor_history.get_current();
3174 if (id != history_id) {
3175 const MultiNodeEdit *multi_node_edit = Object::cast_to<const MultiNodeEdit>(p_object);
3176 const MultiNodeEdit *history_multi_node_edit = ObjectDB::get_instance<MultiNodeEdit>(history_id);
3177 if (multi_node_edit && history_multi_node_edit && multi_node_edit->is_same_selection(history_multi_node_edit)) {
3178 return;
3179 }
3180 if (p_inspector_only) {
3181 editor_history.add_object(id, String(), true);
3182 } else if (p_property.is_empty()) {
3183 editor_history.add_object(id);
3184 } else {
3185 editor_history.add_object(id, p_property);
3186 }
3187 }
3188}
3189
3190void EditorNode::_edit_current(bool p_skip_foreign, bool p_skip_inspector_update) {
3191 ObjectID current_id = editor_history.get_current();
3192 Object *current_obj = current_id.is_valid() ? ObjectDB::get_instance(current_id) : nullptr;
3193
3194 Ref<Resource> res = Object::cast_to<Resource>(current_obj);
3195 if (p_skip_foreign && res.is_valid()) {
3196 const int current_tab = scene_tabs->get_current_tab();
3197 if (res->get_path().contains("::") && res->get_path().get_slice("::", 0) != editor_data.get_scene_path(current_tab)) {
3198 // Trying to edit resource that belongs to another scene; abort.
3199 current_obj = nullptr;
3200 }
3201 }
3202
3203 bool inspector_only = editor_history.is_current_inspector_only();
3204
3205 if (!current_obj) {
3206 SceneTreeDock::get_singleton()->set_selected(nullptr);
3207 InspectorDock::get_inspector_singleton()->edit(nullptr);
3208 SignalsDock::get_singleton()->set_object(nullptr);
3209 GroupsDock::get_singleton()->set_selection(Vector<Node *>());
3210 InspectorDock::get_singleton()->update(nullptr);
3211 EditorDebuggerNode::get_singleton()->clear_remote_tree_selection();
3212 hide_unused_editors();
3213 return;
3214 }
3215
3216 // Update the use folding setting and state.
3217 bool disable_folding = EDITOR_GET("interface/inspector/disable_folding");
3218 if (InspectorDock::get_inspector_singleton()->is_using_folding() == disable_folding) {
3219 InspectorDock::get_inspector_singleton()->set_use_folding(!disable_folding, false);
3220 }
3221
3222 bool is_resource = Object::cast_to<Resource>(current_obj);
3223 bool is_node = Object::cast_to<Node>(current_obj);
3224
3225 String editable_info; // None by default.
3226 bool info_is_warning = false;
3227
3228 if (current_obj->call(SNAME("_is_read_only")).operator bool()) {
3229 editable_info = TTR("This object is marked as read-only, so it's not editable.");
3230 }
3231
3232 if (is_resource) {
3233 Resource *current_res = Object::cast_to<Resource>(current_obj);
3234 ERR_FAIL_NULL(current_res);
3235
3236 if (!p_skip_inspector_update) {
3237 InspectorDock::get_inspector_singleton()->edit(current_res);
3238 SceneTreeDock::get_singleton()->set_selected(nullptr);
3239 SignalsDock::get_singleton()->set_object(current_res);
3240 GroupsDock::get_singleton()->set_selection(Vector<Node *>());
3241 InspectorDock::get_singleton()->update(nullptr);
3242 EditorDebuggerNode::get_singleton()->clear_remote_tree_selection();
3243 ImportDock::get_singleton()->set_edit_path(current_res->get_path());
3244 }
3245
3246 int subr_idx = current_res->get_path().find("::");
3247 if (subr_idx != -1) {
3248 String base_path = current_res->get_path().substr(0, subr_idx);
3249 if (FileAccess::exists(base_path + ".import")) {
3250 if (!base_path.is_resource_file()) {
3251 if (get_edited_scene() && get_edited_scene()->get_scene_file_path() == base_path) {
3252 info_is_warning = true;
3253 }
3254 }
3255 editable_info = TTR("This resource belongs to a scene that was imported, so it's not editable.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
3256 } else if ((!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base_path) && ResourceLoader::get_resource_type(base_path) == "PackedScene") {
3257 editable_info = TTR("This resource belongs to a scene that was instantiated or inherited.\nChanges to it must be made inside the original scene.");
3258 }
3259 } else if (current_res->get_path().is_resource_file()) {
3260 if (FileAccess::exists(current_res->get_path() + ".import")) {
3261 editable_info = TTR("This resource was imported, so it's not editable. Change its settings in the import panel and then re-import.");
3262 }
3263 }
3264 } else if (is_node) {
3265 Node *current_node = Object::cast_to<Node>(current_obj);
3266 ERR_FAIL_NULL(current_node);
3267
3268 InspectorDock::get_inspector_singleton()->edit(current_node);
3269 if (current_node->is_inside_tree()) {
3270 SignalsDock::get_singleton()->set_object(current_node);
3271 GroupsDock::get_singleton()->set_selection(Vector<Node *>{ current_node });
3272 SceneTreeDock::get_singleton()->set_selected(current_node);
3273 SceneTreeDock::get_singleton()->set_selection({ current_node });
3274 InspectorDock::get_singleton()->update(current_node);
3275 } else {
3276 SignalsDock::get_singleton()->set_object(nullptr);
3277 GroupsDock::get_singleton()->set_selection(Vector<Node *>());
3278 SceneTreeDock::get_singleton()->set_selected(nullptr);
3279 InspectorDock::get_singleton()->update(nullptr);
3280 }
3281 EditorDebuggerNode::get_singleton()->clear_remote_tree_selection();
3282
3283 if (get_edited_scene() && !get_edited_scene()->get_scene_file_path().is_empty()) {
3284 String source_scene = get_edited_scene()->get_scene_file_path();
3285 if (FileAccess::exists(source_scene + ".import")) {
3286 editable_info = TTR("This scene was imported, so changes to it won't be kept.\nInstantiating or inheriting it will allow you to make changes to it.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
3287 info_is_warning = true;
3288 }
3289 }
3290 } else {
3291 Node *selected_node = nullptr;
3292
3293 Vector<Node *> multi_nodes;
3294 if (current_obj->is_class("MultiNodeEdit")) {
3295 Node *scene = get_edited_scene();
3296 if (scene) {
3297 MultiNodeEdit *multi_node_edit = Object::cast_to<MultiNodeEdit>(current_obj);
3298 int node_count = multi_node_edit->get_node_count();
3299 if (node_count > 0) {
3300 for (int node_index = 0; node_index < node_count; ++node_index) {
3301 Node *node = scene->get_node(multi_node_edit->get_node(node_index));
3302 if (node) {
3303 multi_nodes.push_back(node);
3304 }
3305 }
3306 if (!multi_nodes.is_empty()) {
3307 // Pick the top-most node.
3308 selected_node = multi_nodes[0];
3309 Node::Comparator comparator;
3310 for (Node *node : multi_nodes) {
3311 if (comparator(node, selected_node)) {
3312 selected_node = node;
3313 }
3314 }
3315 }
3316 }
3317 }
3318 }
3319
3320 if (!current_obj->is_class("EditorDebuggerRemoteObjects")) {
3321 EditorDebuggerNode::get_singleton()->clear_remote_tree_selection();
3322 }
3323
3324 InspectorDock::get_inspector_singleton()->edit(current_obj);
3325 SignalsDock::get_singleton()->set_object(nullptr);
3326 GroupsDock::get_singleton()->set_selection(multi_nodes);
3327 SceneTreeDock::get_singleton()->set_selected(selected_node);
3328 SceneTreeDock::get_singleton()->set_selection(multi_nodes);
3329 InspectorDock::get_singleton()->update(nullptr);
3330 }
3331
3332 InspectorDock::get_singleton()->set_info(
3333 info_is_warning ? TTR("Changes may be lost!") : TTR("This object is read-only."),
3334 editable_info,
3335 info_is_warning);
3336
3337 Object *editor_owner = (is_node || current_obj->is_class("MultiNodeEdit")) ? (Object *)SceneTreeDock::get_singleton() : is_resource ? (Object *)InspectorDock::get_inspector_singleton()
3338 : (Object *)this;
3339
3340 // Take care of the main editor plugin.
3341
3342 if (!inspector_only) {
3343 edit_item(current_obj, editor_owner);
3344 }
3345
3346 InspectorDock::get_singleton()->update(current_obj);
3347}
3348
3349void EditorNode::_android_build_source_selected(const String &p_file) {
3350 export_template_manager->install_android_template_from_file(p_file, android_export_preset);
3351}
3352
3353void EditorNode::_android_export_preset_selected(int p_index) {
3354 if (p_index >= 0) {
3355 android_export_preset = EditorExport::get_singleton()->get_export_preset(choose_android_export_profile->get_item_id(p_index));
3356 } else {
3357 android_export_preset.unref();
3358 }
3359 install_android_build_template_message->set_text(vformat(TTR(INSTALL_ANDROID_BUILD_TEMPLATE_MESSAGE), export_template_manager->get_android_build_directory(android_export_preset)));
3360}
3361
3362void EditorNode::_android_install_build_template() {
3363 gradle_build_manage_templates->hide();
3364 file_android_build_source->popup_centered_ratio();
3365}
3366
3367void EditorNode::_android_explore_build_templates() {
3368 OS::get_singleton()->shell_show_in_file_manager(ProjectSettings::get_singleton()->globalize_path(export_template_manager->get_android_build_directory(android_export_preset).get_base_dir()), true);
3369}
3370
3371void EditorNode::_android_remove_build_templates(bool p_prompt_for_removal) {
3372 String removal_text = ANDROID_BUILD_TEMPLATE_ALREADY_INSTALLED_MESSAGE;
3373 if (p_prompt_for_removal) {
3374 removal_text += "\n" + vformat(TTR(REMOVE_ANDROID_BUILD_TEMPLATE_MESSAGE), export_template_manager->get_android_build_directory(android_export_preset));
3375 }
3376 remove_android_build_template->set_text(removal_text);
3377 remove_android_build_template->popup_centered_clamped(Size2(600, 200) * EDSCALE, 0.7);
3378}
3379
3380void EditorNode::_setup_android_build(bool p_confirmed) {
3381 if (p_confirmed) {
3382 setup_android_build_template(android_export_preset, p_confirmed);
3383 } else {
3384 bool has_custom_gradle_build = false;
3385 choose_android_export_profile->clear();
3386 for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
3387 Ref<EditorExportPreset> export_preset = EditorExport::get_singleton()->get_export_preset(i);
3388 if (export_preset->get_platform()->get_class_name() == "EditorExportPlatformAndroid" && (bool)export_preset->get("gradle_build/use_gradle_build")) {
3389 choose_android_export_profile->add_item(export_preset->get_name(), i);
3390 String gradle_build_directory = export_preset->get("gradle_build/gradle_build_directory");
3391 String android_source_template = export_preset->get("gradle_build/android_source_template");
3392 if (!android_source_template.is_empty() || (gradle_build_directory != "" && gradle_build_directory != "res://android")) {
3393 has_custom_gradle_build = true;
3394 }
3395 }
3396 }
3397 _android_export_preset_selected(choose_android_export_profile->get_item_count() >= 1 ? 0 : -1);
3398
3399 if (choose_android_export_profile->get_item_count() > 1 && has_custom_gradle_build) {
3400 // If there's multiple options and at least one of them uses a custom gradle build then prompt the user to choose.
3401 choose_android_export_profile->show();
3402 install_android_build_template->popup_centered();
3403 } else {
3404 choose_android_export_profile->hide();
3405
3406 setup_android_build_template(android_export_preset, p_confirmed);
3407 }
3408 }
3409}
3410
3411Error EditorNode::setup_android_build_template(const Ref<EditorExportPreset> &p_preset, bool p_confirmed) {
3412 android_export_preset = p_preset;
3413 if (export_template_manager->is_android_template_installed(p_preset)) {
3414 if (export_template_manager->is_android_build_version_valid(p_preset)) {
3415 if (!p_confirmed) {
3416 // The setup is valid, maybe the user wants to delete and reinstall it...
3417 _android_remove_build_templates(false);
3418 }
3419 return OK;
3420 }
3421
3422 // If we get here, then the installed android build directory is no longer valid (e.g. editor upgrade).
3423 // Let's check whether we can automatically delete the build directory. If not, we return an error and let the
3424 // user handle the deletion.
3425 bool can_delete_automatically = EDITOR_GET("export/android/build/automatically_delete_build_directory");
3426 if (can_delete_automatically) {
3427 if (!p_confirmed) {
3428 install_android_build_template->popup_centered();
3429 return ERR_UNCONFIGURED;
3430 }
3431
3432 if (export_template_manager->delete_android_build_directory(android_export_preset) == OK) {
3433 return setup_android_build_template(android_export_preset, p_confirmed);
3434 }
3435 }
3436
3437 // If we get here, we need to prompt the user to delete the android build directory, either because we cannot do
3438 // it automatically, or because we tried to do it automatically and failed.
3439 _android_remove_build_templates(true);
3440 return ERR_UNCONFIGURED;
3441 } else if (!export_template_manager->can_install_android_template(p_preset)) {
3442 gradle_build_manage_templates->popup_centered();
3443 } else {
3444 if (p_confirmed) {
3445 return export_template_manager->install_android_template(p_preset);
3446 } else {
3447 install_android_build_template->popup_centered();
3448 }
3449 }
3450
3451 return ERR_UNCONFIGURED;
3452}
3453
3454static String _get_unsaved_scene_dialog_text(String p_scene_filename, uint64_t p_opened_timestamp) {
3455 const uint64_t scene_modified_time = FileAccess::get_modified_time(p_scene_filename);
3456 String unsaved_message;
3457
3458 // Consider scene opening to be a point of saving, so that when you
3459 // close and reopen the editor, you don't get an excessively long
3460 // "modified X hours ago".
3461 const uint64_t last_modified_seconds = Time::get_singleton()->get_unix_time_from_system() - MAX(p_opened_timestamp, scene_modified_time);
3462
3463 String last_modified_string;
3464 if (last_modified_seconds < 120) {
3465 last_modified_string = vformat(TTRN("%d second ago", "%d seconds ago", last_modified_seconds), last_modified_seconds);
3466 } else if (last_modified_seconds < 7200) {
3467 last_modified_string = vformat(TTRN("%d minute ago", "%d minutes ago", last_modified_seconds / 60), last_modified_seconds / 60);
3468 } else {
3469 last_modified_string = vformat(TTRN("%d hour ago", "%d hours ago", last_modified_seconds / 3600), last_modified_seconds / 3600);
3470 }
3471
3472 String last_action_and_time;
3473 if (p_opened_timestamp > scene_modified_time) {
3474 last_action_and_time = vformat(TTR("Scene opened: %s."), last_modified_string);
3475 } else {
3476 last_action_and_time = vformat(TTR("Last saved: %s."), last_modified_string);
3477 }
3478
3479 unsaved_message = vformat(TTR("Scene \"%s\" has unsaved changes.\n%s"), p_scene_filename, last_action_and_time);
3480
3481 return unsaved_message;
3482}
3483
3484void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
3485 if (!p_confirmed) { // FIXME: this may be a hack.
3486 current_menu_option = (MenuOptions)p_option;
3487 }
3488
3489 constexpr int button_mask_full = int(MouseButtonMask::LEFT | MouseButtonMask::RIGHT | MouseButtonMask::MIDDLE | MouseButtonMask::MB_XBUTTON1 | MouseButtonMask::MB_XBUTTON2);
3490
3491 switch (p_option) {
3492 case SCENE_NEW_SCENE: {
3493 new_scene();
3494
3495 } break;
3496 case SCENE_NEW_INHERITED_SCENE:
3497 case SCENE_OPEN_SCENE: {
3498 file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
3499 List<String> extensions;
3500 ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
3501 file->clear_filters();
3502 for (const String &extension : extensions) {
3503 file->add_filter("*." + extension, extension.to_upper());
3504 }
3505
3506 Node *scene = editor_data.get_edited_scene_root();
3507 if (scene) {
3508 file->set_current_path(scene->get_scene_file_path());
3509 };
3510 file->set_title(p_option == SCENE_OPEN_SCENE ? TTR("Open Scene") : TTR("Open Base Scene"));
3511 file->popup_file_dialog();
3512
3513 } break;
3514 case SCENE_QUICK_OPEN: {
3515 quick_open_dialog->popup_dialog({ "Resource" }, callable_mp(this, &EditorNode::_quick_opened), true);
3516 } break;
3517 case SCENE_QUICK_OPEN_SCENE: {
3518 quick_open_dialog->popup_dialog({ "PackedScene" }, callable_mp(this, &EditorNode::_quick_opened), true);
3519 } break;
3520 case SCENE_QUICK_OPEN_SCRIPT: {
3521 quick_open_dialog->popup_dialog({ "Script" }, callable_mp(this, &EditorNode::_quick_opened), true);
3522 } break;
3523 case SCENE_OPEN_PREV: {
3524 if (!prev_closed_scenes.is_empty()) {
3525 String path = prev_closed_scenes[prev_closed_scenes.size() - 1];
3526 path = ResourceUID::ensure_path_nocheck(path);
3527 if (!path.is_empty() && ResourceLoader::exists(path)) {
3528 open_scene(path);
3529 } else {
3530 prev_closed_scenes.resize(prev_closed_scenes.size() - 1);
3531 }
3532 }
3533 } break;
3534 case EditorSceneTabs::SCENE_CLOSE_OTHERS: {
3535 tab_closing_menu_option = -1;
3536 int option_tab = scene_tabs->get_option_tab();
3537 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
3538 if (i == option_tab) {
3539 continue;
3540 }
3541 tabs_to_close.push_back(editor_data.get_scene_path(i));
3542 }
3543 _proceed_closing_scene_tabs();
3544 } break;
3545 case EditorSceneTabs::SCENE_CLOSE_RIGHT: {
3546 tab_closing_menu_option = -1;
3547 for (int i = scene_tabs->get_option_tab() + 1; i < editor_data.get_edited_scene_count(); i++) {
3548 tabs_to_close.push_back(editor_data.get_scene_path(i));
3549 }
3550 _proceed_closing_scene_tabs();
3551 } break;
3552 case SCENE_CLOSE_ALL: {
3553 tab_closing_menu_option = -1;
3554 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
3555 tabs_to_close.push_back(editor_data.get_scene_path(i));
3556 }
3557 _proceed_closing_scene_tabs();
3558 } break;
3559 case SCENE_CLOSE: {
3560 _scene_tab_closed(editor_data.get_edited_scene());
3561 } break;
3562 case EditorSceneTabs::SCENE_CLOSE: {
3563 _scene_tab_closed(scene_tabs->get_option_tab());
3564 } break;
3565 case SCENE_TAB_CLOSE:
3566 case SCENE_SAVE_SCENE:
3567 case EditorSceneTabs::SCENE_SAVE_SCENE: {
3568 int scene_idx = -1;
3569 if (p_option == SCENE_TAB_CLOSE) {
3570 scene_idx = tab_closing_idx;
3571 } else if (p_option == EditorSceneTabs::SCENE_SAVE_SCENE) {
3572 scene_idx = scene_tabs->get_option_tab();
3573 }
3574 Node *scene = editor_data.get_edited_scene_root(scene_idx);
3575
3576 if (scene && !scene->get_scene_file_path().is_empty()) {
3577 if (DirAccess::exists(scene->get_scene_file_path().get_base_dir())) {
3578 if (scene_idx != editor_data.get_edited_scene()) {
3579 _save_scene_with_preview(scene->get_scene_file_path(), scene_idx);
3580 } else {
3581 _save_scene_with_preview(scene->get_scene_file_path());
3582 }
3583
3584 if (scene_idx != -1) {
3585 _discard_changes();
3586 }
3587 save_editor_layout_delayed();
3588 } else {
3589 show_save_accept(vformat(TTR("%s no longer exists! Please specify a new save location."), scene->get_scene_file_path().get_base_dir()));
3590 }
3591 break;
3592 }
3593 [[fallthrough]];
3594 }
3595 case SCENE_MULTI_SAVE_AS_SCENE:
3596 case SCENE_SAVE_AS_SCENE:
3597 case EditorSceneTabs::SCENE_SAVE_AS_SCENE: {
3598 int scene_idx = -1;
3599 if (p_option == SCENE_TAB_CLOSE) {
3600 scene_idx = tab_closing_idx;
3601 } else if (p_option == EditorSceneTabs::SCENE_SAVE_SCENE || p_option == EditorSceneTabs::SCENE_SAVE_AS_SCENE) {
3602 scene_idx = scene_tabs->get_option_tab();
3603 current_menu_option = SCENE_TAB_SAVE_SCENE;
3604 }
3605 Node *scene = editor_data.get_edited_scene_root(scene_idx);
3606 if (!scene) {
3607 if (p_option == SCENE_SAVE_SCENE) {
3608 // Pressing Ctrl + S saves the current script if a scene is currently open, but it won't if the scene has no root node.
3609 // Work around this by explicitly saving the script in this case (similar to pressing Ctrl + Alt + S).
3610 ScriptEditor::get_singleton()->save_current_script();
3611 }
3612
3613 const int saved = _save_external_resources(true);
3614 if (saved > 0) {
3615 EditorToaster::get_singleton()->popup_str(vformat(TTR("The current scene has no root node, but %d modified external resource(s) and/or plugin data were saved anyway."), saved), EditorToaster::SEVERITY_INFO);
3616 } else if (p_option == SCENE_SAVE_AS_SCENE) {
3617 // Don't show this dialog when pressing Ctrl + S to avoid interfering with script saving.
3618 show_warning(TTR("A root node is required to save the scene. You can add a root node using the Scene dock."));
3619 }
3620
3621 break;
3622 }
3623
3624 file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
3625
3626 List<String> extensions;
3627 Ref<PackedScene> sd = memnew(PackedScene);
3628 ResourceSaver::get_recognized_extensions(sd, &extensions);
3629 file->clear_filters();
3630 for (const String &extension : extensions) {
3631 file->add_filter("*." + extension, extension.to_upper());
3632 }
3633
3634 if (!scene->get_scene_file_path().is_empty()) {
3635 String path = scene->get_scene_file_path();
3636 String root_name = EditorNode::adjust_scene_name_casing(scene->get_name());
3637 String ext = path.get_extension().to_lower();
3638 path = path.get_base_dir().path_join(root_name + "." + ext);
3639
3640 file->set_current_path(path);
3641 if (extensions.size()) {
3642 if (extensions.find(ext) == nullptr) {
3643 file->set_current_path(path.replacen("." + ext, "." + extensions.front()->get()));
3644 }
3645 }
3646 } else if (extensions.size()) {
3647 String root_name = scene->get_name();
3648 root_name = EditorNode::adjust_scene_name_casing(root_name);
3649 file->set_current_path(root_name + "." + extensions.front()->get().to_lower());
3650 }
3651 file->set_title(TTR("Save Scene As..."));
3652 file->popup_file_dialog();
3653
3654 } break;
3655
3656 case EditorSceneTabs::SCENE_SET_AS_MAIN_SCENE: {
3657 const String scene_path = editor_data.get_scene_path(scene_tabs->get_option_tab());
3658 if (scene_path.is_empty()) {
3659 _menu_option_confirm(EditorSceneTabs::SCENE_SAVE_AS_SCENE, true);
3660 current_menu_option = SCENE_TAB_SAVE_AS_MAIN_SCENE; // Overwrites SCENE_TAB_SAVE_SCENE.
3661 file->set_title(TTR("Save new main scene..."));
3662 } else {
3663 ProjectSettings::get_singleton()->set("application/run/main_scene", ResourceUID::path_to_uid(scene_path));
3664 ProjectSettings::get_singleton()->save();
3665 FileSystemDock::get_singleton()->update_all();
3666 }
3667 } break;
3668
3669 case SCENE_SAVE_ALL_SCENES: {
3670 _save_all_scenes();
3671 } break;
3672
3673 case EditorSceneTabs::SCENE_RUN: {
3674 Node *scene = editor_data.get_edited_scene_root(scene_tabs->get_option_tab());
3675 ERR_FAIL_NULL(scene);
3676
3677 const String &scene_path = scene->get_scene_file_path();
3678 if (scene_path.is_empty()) {
3679 _menu_option_confirm(EditorSceneTabs::SCENE_SAVE_AS_SCENE, true);
3680 current_menu_option = SCENE_TAB_SAVE_AS_AND_RUN; // Overwrites SCENE_TAB_SAVE_SCENE.
3681 file->set_title(TTR("Save scene before running..."));
3682 } else {
3683 project_run_bar->play_custom_scene(scene_path);
3684 }
3685 } break;
3686
3687 case PROJECT_EXPORT: {
3688 project_export->popup_export();
3689 } break;
3690
3691 case PROJECT_PACK_AS_ZIP: {
3692 String resource_path = ProjectSettings::get_singleton()->get_resource_path();
3693 const String base_path = resource_path.substr(0, resource_path.rfind_char('/')) + "/";
3694
3695 file_pack_zip->set_current_path(base_path);
3696 file_pack_zip->set_current_file(ProjectZIPPacker::get_project_zip_safe_name());
3697 file_pack_zip->popup_file_dialog();
3698 } break;
3699
3700 case SCENE_UNDO: {
3701 if ((int)Input::get_singleton()->get_mouse_button_mask() & button_mask_full) {
3702 log->add_message(TTR("Can't undo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
3703 } else {
3704 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
3705 String action = undo_redo->get_current_action_name();
3706 int id = undo_redo->get_current_action_history_id();
3707 if (!undo_redo->undo()) {
3708 log->add_message(TTR("Nothing to undo."), EditorLog::MSG_TYPE_EDITOR);
3709 } else if (!action.is_empty()) {
3710 switch (id) {
3711 case EditorUndoRedoManager::GLOBAL_HISTORY:
3712 log->add_message(vformat(TTR("Global Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3713 break;
3714 case EditorUndoRedoManager::REMOTE_HISTORY:
3715 log->add_message(vformat(TTR("Remote Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3716 break;
3717 default:
3718 log->add_message(vformat(TTR("Scene Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3719 }
3720 }
3721 }
3722 _update_unsaved_cache();
3723 } break;
3724 case SCENE_REDO: {
3725 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
3726 if ((int)Input::get_singleton()->get_mouse_button_mask() & button_mask_full) {
3727 log->add_message(TTR("Can't redo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
3728 } else {
3729 if (!undo_redo->redo()) {
3730 log->add_message(TTR("Nothing to redo."), EditorLog::MSG_TYPE_EDITOR);
3731 } else {
3732 String action = undo_redo->get_current_action_name();
3733 if (action.is_empty()) {
3734 break;
3735 }
3736
3737 switch (undo_redo->get_current_action_history_id()) {
3738 case EditorUndoRedoManager::GLOBAL_HISTORY:
3739 log->add_message(vformat(TTR("Global Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3740 break;
3741 case EditorUndoRedoManager::REMOTE_HISTORY:
3742 log->add_message(vformat(TTR("Remote Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3743 break;
3744 default:
3745 log->add_message(vformat(TTR("Scene Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
3746 }
3747 }
3748 }
3749 _update_unsaved_cache();
3750 } break;
3751
3752 case SCENE_RELOAD_SAVED_SCENE: {
3753 const int p_idx = editor_data.get_edited_scene();
3754 const uint64_t scene_time_opened = editor_data.get_scene_time_opened(p_idx);
3755 const String scene_filename = editor_data.get_scene_path(p_idx);
3756
3757 if (scene_filename.is_empty()) {
3758 show_warning(TTR("Can't reload a scene that was never saved."));
3759 break;
3760 }
3761
3762 if (unsaved_cache) {
3763 if (!p_confirmed) {
3764 confirmation->set_ok_button_text(TTRC("Save & Reload"));
3765 const String unsaved_message = _get_unsaved_scene_dialog_text(scene_filename, scene_time_opened);
3766 confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before reloading the scene?"));
3767 confirmation->popup_centered();
3768 confirmation_button->show();
3769 confirmation_button->grab_focus();
3770 break;
3771 } else {
3772 _save_scene_with_preview(scene_filename);
3773 }
3774 }
3775
3776 _discard_changes();
3777 } break;
3778
3779 case EditorSceneTabs::SCENE_SHOW_IN_FILESYSTEM: {
3780 String path = editor_data.get_scene_path(scene_tabs->get_option_tab());
3781 if (!path.is_empty()) {
3782 FileSystemDock::get_singleton()->navigate_to_path(path);
3783 }
3784 } break;
3785
3786 case PROJECT_OPEN_SETTINGS: {
3787 project_settings_editor->popup_project_settings();
3788 } break;
3789
3790 case PROJECT_FIND_IN_FILES:
3791 case PROJECT_REPLACE_IN_FILES: {
3792 FindInFiles::get_singleton()->open_dock("", PROJECT_REPLACE_IN_FILES == p_option);
3793 } break;
3794
3795 case PROJECT_SETUP_ANDROID_BUILD: {
3796#ifndef ANDROID_ENABLED
3797 if (!(AndroidSDKManager::is_android_sdk_setup() && AndroidSDKManager::is_java_sdk_setup())) {
3798 Callable setup_android_build_callable = callable_mp(this, &EditorNode::_setup_android_build).bind(p_confirmed);
3799 android_sdk_manager->run_setup(setup_android_build_callable, setup_android_build_callable);
3800 } else {
3801#endif
3802 _setup_android_build(p_confirmed);
3803#ifndef ANDROID_ENABLED
3804 }
3805#endif
3806 } break;
3807 case PROJECT_OPEN_USER_DATA_FOLDER: {
3808 // Ensure_user_data_dir() to prevent the edge case: "Open User Data Folder" won't work after the project was renamed in ProjectSettingsEditor unless the project is saved.
3809 OS::get_singleton()->ensure_user_data_dir();
3810 OS::get_singleton()->shell_show_in_file_manager(OS::get_singleton()->get_user_data_dir(), true);
3811 } break;
3812 case PROJECT_DOWNLOAD_SOURCE: {
3813#ifdef WEB_ENABLED
3814 const String output_name = ProjectZIPPacker::get_project_zip_safe_name();
3815 const String output_path = String("/tmp").path_join(output_name);
3816 ProjectZIPPacker::pack_project_zip(output_path);
3817
3818 {
3819 Ref<FileAccess> f = FileAccess::open(output_path, FileAccess::READ);
3820 ERR_FAIL_COND_MSG(f.is_null(), "Unable to create ZIP file.");
3821 LocalVector<uint8_t> buf;
3822 buf.resize(f->get_length());
3823 f->get_buffer(buf.ptr(), buf.size());
3824 godot_js_os_download_buffer(buf.ptr(), buf.size(), output_name.utf8().get_data(), "application/zip");
3825 }
3826
3827 // Remove the temporary file since it was sent to the user's native filesystem as a download.
3828 DirAccess::remove_file_or_error(output_path);
3829#endif
3830 } break;
3831 case SCENE_QUIT:
3832 case PROJECT_QUIT_TO_PROJECT_MANAGER:
3833 case TOOLS_CLEAR_PROJECT_CACHE:
3834 case PROJECT_RELOAD_CURRENT_PROJECT: {
3835 if (p_confirmed && plugin_to_save) {
3836 plugin_to_save->save_external_data();
3837 p_confirmed = false;
3838 }
3839
3840 if (p_confirmed && stop_project_confirmation && project_run_bar->is_playing()) {
3841 project_run_bar->stop_playing();
3842 stop_project_confirmation = false;
3843 p_confirmed = false;
3844 }
3845
3846 if (p_confirmed && stop_download_confirmation && export_template_manager->is_downloading()) {
3847 export_template_manager->stop_download();
3848 stop_download_confirmation = false;
3849 p_confirmed = false;
3850 }
3851
3852 bool is_restart = (p_option == PROJECT_RELOAD_CURRENT_PROJECT || p_option == TOOLS_CLEAR_PROJECT_CACHE);
3853 if (!p_confirmed) {
3854 if (!stop_project_confirmation && project_run_bar->is_playing()) {
3855 if (is_restart) {
3856 confirmation->set_text(TTR("Stop running project before reloading the current project?"));
3857 confirmation->set_ok_button_text(TTR("Stop & Reload"));
3858 } else {
3859 confirmation->set_text(TTR("Stop running project before exiting the editor?"));
3860 confirmation->set_ok_button_text(TTR("Stop & Quit"));
3861 }
3862 confirmation_button->hide();
3863 confirmation->reset_size();
3864 confirmation->popup_centered();
3865 stop_project_confirmation = true;
3866 break;
3867 }
3868
3869 if (!stop_download_confirmation && export_template_manager->is_downloading()) {
3870 confirmation->set_text(TTR("The export templates are still being downloaded."));
3871 if (is_restart) {
3872 confirmation->set_ok_button_text(TTR("Stop & Reload"));
3873 } else {
3874 confirmation->set_ok_button_text(TTR("Stop & Quit"));
3875 }
3876 confirmation_button->hide();
3877 confirmation->reset_size();
3878 confirmation->popup_centered();
3879 stop_download_confirmation = true;
3880 break;
3881 }
3882
3883 bool save_each = EDITOR_GET("interface/editor/behavior/save_each_scene_on_quit");
3884 if (_next_unsaved_scene(!save_each) == -1) {
3885 if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY)) {
3886 if (is_restart) {
3887 save_confirmation->set_ok_button_text(TTR("Save & Reload"));
3888 save_confirmation->set_text(TTR("Save modified resources before reloading?"));
3889 } else {
3890 save_confirmation->set_ok_button_text(TTR("Save & Quit"));
3891 save_confirmation->set_text(TTR("Save modified resources before closing?"));
3892 }
3893 save_confirmation->reset_size();
3894 save_confirmation->popup_centered();
3895 break;
3896 }
3897
3898 plugin_to_save = nullptr;
3899 for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
3900 const String unsaved_status = editor_data.get_editor_plugin(i)->get_unsaved_status();
3901 if (!unsaved_status.is_empty()) {
3902 if (is_restart) {
3903 save_confirmation->set_ok_button_text(TTR("Save & Reload"));
3904 save_confirmation->set_text(unsaved_status);
3905 } else {
3906 save_confirmation->set_ok_button_text(TTR("Save & Quit"));
3907 save_confirmation->set_text(unsaved_status);
3908 }
3909 save_confirmation->reset_size();
3910 save_confirmation->popup_centered();
3911 plugin_to_save = editor_data.get_editor_plugin(i);
3912 break;
3913 }
3914 }
3915
3916 if (plugin_to_save) {
3917 break;
3918 }
3919
3920 _discard_changes();
3921 break;
3922 }
3923
3924 if (save_each) {
3925 tab_closing_menu_option = current_menu_option;
3926 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
3927 tabs_to_close.push_back(editor_data.get_scene_path(i));
3928 }
3929 _proceed_closing_scene_tabs();
3930 } else {
3931 String unsaved_scenes;
3932 int i = _next_unsaved_scene(true, 0);
3933 while (i != -1) {
3934 unsaved_scenes += "\n " + editor_data.get_edited_scene_root(i)->get_scene_file_path();
3935 i = _next_unsaved_scene(true, ++i);
3936 }
3937 if (is_restart) {
3938 save_confirmation->set_ok_button_text(TTR("Save & Reload"));
3939 save_confirmation->set_text(TTR("Save changes to the following scene(s) before reloading?") + unsaved_scenes);
3940 } else {
3941 save_confirmation->set_ok_button_text(TTR("Save & Quit"));
3942 save_confirmation->set_text((p_option == SCENE_QUIT ? TTR("Save changes to the following scene(s) before quitting?") : TTR("Save changes to the following scene(s) before opening Project Manager?")) + unsaved_scenes);
3943 }
3944 save_confirmation->reset_size();
3945 save_confirmation->popup_centered();
3946 }
3947
3948 DisplayServer::get_singleton()->window_request_attention();
3949 break;
3950 }
3951 _save_external_resources();
3952 _discard_changes();
3953 } break;
3954 case SPINNER_UPDATE_CONTINUOUSLY: {
3955 EditorSettings::get_singleton()->set("interface/editor/display/update_continuously", true);
3956 _update_update_spinner();
3957 show_warning(TTR("This option is deprecated. Situations where refresh must be forced are now considered a bug. Please report."));
3958 } break;
3959 case SPINNER_UPDATE_WHEN_CHANGED: {
3960 EditorSettings::get_singleton()->set("interface/editor/display/update_continuously", false);
3961 _update_update_spinner();
3962 } break;
3963 case SPINNER_UPDATE_SPINNER_HIDE: {
3964 EditorSettings::get_singleton()->set("interface/editor/appearance/show_update_spinner", 2); // Disabled
3965 _update_update_spinner();
3966 } break;
3967 case EDITOR_OPEN_SETTINGS: {
3968 editor_settings_dialog->popup_edit_settings();
3969 } break;
3970 case EDITOR_OPEN_DATA_FOLDER: {
3971 OS::get_singleton()->shell_show_in_file_manager(EditorPaths::get_singleton()->get_data_dir(), true);
3972 } break;
3973 case EDITOR_OPEN_CONFIG_FOLDER: {
3974 OS::get_singleton()->shell_show_in_file_manager(EditorPaths::get_singleton()->get_config_dir(), true);
3975 } break;
3976 case EDITOR_MANAGE_EXPORT_TEMPLATES: {
3977 export_template_manager->popup_manager();
3978 } break;
3979 case EDITOR_CONFIGURE_FBX_IMPORTER: {
3980#if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
3981 fbx_importer_manager->show_dialog();
3982#endif
3983 } break;
3984 case EDITOR_MANAGE_FEATURE_PROFILES: {
3985 feature_profile_manager->popup_centered_clamped(Size2(900, 800) * EDSCALE, 0.8);
3986 } break;
3987 case EDITOR_TOGGLE_FULLSCREEN: {
3988 DisplayServerEnums::WindowMode mode = DisplayServer::get_singleton()->window_get_mode();
3989 if (mode == DisplayServerEnums::WINDOW_MODE_FULLSCREEN || mode == DisplayServerEnums::WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
3990 DisplayServer::get_singleton()->window_set_mode(prev_mode);
3991#ifdef ANDROID_ENABLED
3992 EditorSettings::get_singleton()->set("_is_editor_fullscreen", false);
3993 EditorSettings::get_singleton()->save();
3994#endif
3995 } else {
3996 prev_mode = mode;
3997 DisplayServer::get_singleton()->window_set_mode(DisplayServerEnums::WINDOW_MODE_FULLSCREEN);
3998#ifdef ANDROID_ENABLED
3999 EditorSettings::get_singleton()->set("_is_editor_fullscreen", true);
4000 EditorSettings::get_singleton()->save();
4001#endif
4002 }
4003 } break;
4004 case EDITOR_TAKE_SCREENSHOT: {
4005 screenshot_timer->start();
4006 } break;
4007 case SETTINGS_PICK_MAIN_SCENE: {
4008 file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
4009 List<String> extensions;
4010 ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
4011 file->clear_filters();
4012 for (const String &extension : extensions) {
4013 file->add_filter("*." + extension, extension.to_upper());
4014 }
4015
4016 Node *scene = editor_data.get_edited_scene_root();
4017 if (scene) {
4018 file->set_current_path(scene->get_scene_file_path());
4019 }
4020 file->set_title(TTR("Pick a Main Scene"));
4021 file->popup_file_dialog();
4022
4023 } break;
4024 case HELP_SEARCH: {
4025 emit_signal(SNAME("request_help_search"), "");
4026 } break;
4027 case EDITOR_COMMAND_PALETTE: {
4028 command_palette->open_popup();
4029 } break;
4030 case HELP_DOCS: {
4031 OS::get_singleton()->shell_open(GODOT_VERSION_DOCS_URL "/");
4032 } break;
4033 case HELP_FORUM: {
4034 OS::get_singleton()->shell_open("https://forum.godotengine.org/");
4035 } break;
4036 case HELP_REPORT_A_BUG: {
4037 OS::get_singleton()->shell_open("https://github.com/godotengine/godot/issues");
4038 } break;
4039 case HELP_COPY_SYSTEM_INFO: {
4040 String info = _get_system_info();
4041 DisplayServer::get_singleton()->clipboard_set(info);
4042 } break;
4043 case HELP_SUGGEST_A_FEATURE: {
4044 OS::get_singleton()->shell_open("https://github.com/godotengine/godot-proposals#readme");
4045 } break;
4046 case HELP_SEND_DOCS_FEEDBACK: {
4047 OS::get_singleton()->shell_open("https://github.com/godotengine/godot-docs/issues");
4048 } break;
4049 case HELP_COMMUNITY: {
4050 OS::get_singleton()->shell_open("https://godotengine.org/community");
4051 } break;
4052 case HELP_ABOUT: {
4053 if (!about) {
4054 about = memnew(EditorAbout);
4055 gui_base->add_child(about);
4056 }
4057 about->popup_centered(Size2(780, 500) * EDSCALE);
4058 } break;
4059 case HELP_SUPPORT_GODOT_DEVELOPMENT: {
4060 OS::get_singleton()->shell_open("https://fund.godotengine.org/?ref=help_menu");
4061 } break;
4062 }
4063}
4064
4065String EditorNode::adjust_scene_name_casing(const String &p_root_name) {
4066 switch (GLOBAL_GET("editor/naming/scene_name_casing").operator int()) {
4067 case SCENE_NAME_CASING_AUTO:
4068 // Use casing of the root node.
4069 break;
4070 case SCENE_NAME_CASING_PASCAL_CASE:
4071 return p_root_name.to_pascal_case();
4072 case SCENE_NAME_CASING_SNAKE_CASE:
4073 return p_root_name.to_snake_case();
4074 case SCENE_NAME_CASING_KEBAB_CASE:
4075 return p_root_name.to_kebab_case();
4076 case SCENE_NAME_CASING_CAMEL_CASE:
4077 return p_root_name.to_camel_case();
4078 }
4079 return p_root_name;
4080}
4081
4082String EditorNode::adjust_script_name_casing(const String &p_file_name, ScriptLanguage::ScriptNameCasing p_auto_casing) {
4083 int editor_casing = GLOBAL_GET("editor/naming/script_name_casing");
4084 if (editor_casing == ScriptLanguage::SCRIPT_NAME_CASING_AUTO) {
4085 // Use the script language's preferred casing.
4086 editor_casing = p_auto_casing;
4087 }
4088
4089 switch (editor_casing) {
4090 case ScriptLanguage::SCRIPT_NAME_CASING_AUTO:
4091 // Script language has no preference, so do not adjust.
4092 break;
4093 case ScriptLanguage::SCRIPT_NAME_CASING_PASCAL_CASE:
4094 return p_file_name.to_pascal_case();
4095 case ScriptLanguage::SCRIPT_NAME_CASING_SNAKE_CASE:
4096 return p_file_name.to_snake_case();
4097 case ScriptLanguage::SCRIPT_NAME_CASING_KEBAB_CASE:
4098 return p_file_name.to_kebab_case();
4099 case ScriptLanguage::SCRIPT_NAME_CASING_CAMEL_CASE:
4100 return p_file_name.to_camel_case();
4101 }
4102 return p_file_name;
4103}
4104
4105void EditorNode::_request_screenshot() {
4106 _screenshot();
4107}
4108
4109void EditorNode::_screenshot(bool p_use_utc) {
4110 String name = "editor_screenshot_" + Time::get_singleton()->get_datetime_string_from_system(p_use_utc).remove_char(':') + ".png";
4111 String path = String("user://") + name;
4112
4113 if (!EditorRun::request_screenshot(callable_mp(this, &EditorNode::_save_screenshot_with_embedded_process).bind(path))) {
4114 _save_screenshot(path);
4115 }
4116}
4117
4118void EditorNode::_save_screenshot_with_embedded_process(int64_t p_w, int64_t p_h, const String &p_emb_path, const Rect2i &p_rect, const String &p_path) {
4119 Viewport *viewport = get_viewport();
4120 ERR_FAIL_NULL_MSG(viewport, "Cannot get a viewport from the EditorNode.");
4121 Ref<ViewportTexture> texture = viewport->get_texture();
4122 ERR_FAIL_COND_MSG(texture.is_null(), "Cannot get a viewport texture from the editor main screen.");
4123 Ref<Image> img = texture->get_image();
4124 ERR_FAIL_COND_MSG(img.is_null(), "Cannot get an image from a viewport texture of the editor main screen.");
4125#ifdef RD_ENABLED
4126 RenderingDevice *rendering_device = RD::get_singleton();
4127 if (rendering_device && RenderingServer::get_singleton()->viewport_is_using_hdr_2d(viewport->get_viewport_rid())) {
4128 img->linear_to_srgb();
4129 }
4130#endif
4131 ERR_FAIL_COND(p_emb_path.is_empty());
4132 Ref<Image> overlay = Image::load_from_file(p_emb_path);
4133 DirAccess::remove_absolute(p_emb_path);
4134 ERR_FAIL_COND_MSG(overlay.is_null(), "Cannot get an image from a embedded process.");
4135 overlay->convert(img->get_format());
4136 overlay->resize(p_rect.size.x, p_rect.size.y);
4137 img->blend_rect(overlay, Rect2i(0, 0, p_w, p_h), p_rect.position);
4138 Error error = img->save_png(p_path);
4139 ERR_FAIL_COND_MSG(error != OK, "Cannot save screenshot to file '" + p_path + "'.");
4140
4141 if (EDITOR_GET("interface/editor/behavior/automatically_open_screenshots")) {
4142 OS::get_singleton()->shell_show_in_file_manager(ProjectSettings::get_singleton()->globalize_path(p_path), true);
4143 }
4144}
4145
4146void EditorNode::_save_screenshot(const String &p_path) {
4147 Viewport *viewport = get_viewport();
4148 ERR_FAIL_NULL_MSG(viewport, "Cannot get a viewport from the EditorNode.");
4149 Ref<ViewportTexture> texture = viewport->get_texture();
4150 ERR_FAIL_COND_MSG(texture.is_null(), "Cannot get a viewport texture from the editor main screen.");
4151 Ref<Image> img = texture->get_image();
4152 ERR_FAIL_COND_MSG(img.is_null(), "Cannot get an image from a viewport texture of the editor main screen.");
4153#ifdef RD_ENABLED
4154 RenderingDevice *rendering_device = RD::get_singleton();
4155 if (rendering_device && RenderingServer::get_singleton()->viewport_is_using_hdr_2d(viewport->get_viewport_rid())) {
4156 img->linear_to_srgb();
4157 }
4158#endif
4159 Error error = img->save_png(p_path);
4160 ERR_FAIL_COND_MSG(error != OK, "Cannot save screenshot to file '" + p_path + "'.");
4161
4162 if (EDITOR_GET("interface/editor/behavior/automatically_open_screenshots")) {
4163 OS::get_singleton()->shell_show_in_file_manager(ProjectSettings::get_singleton()->globalize_path(p_path), true);
4164 }
4165}
4166
4167void EditorNode::_check_system_theme_changed() {
4168 DisplayServer *display_server = DisplayServer::get_singleton();
4169
4170 bool system_theme_changed = false;
4171
4172 if (follow_system_theme) {
4173 if (display_server->get_base_color() != last_system_base_color) {
4174 system_theme_changed = true;
4175 last_system_base_color = display_server->get_base_color();
4176 }
4177
4178 if (display_server->is_dark_mode_supported() && display_server->is_dark_mode() != last_dark_mode_state) {
4179 system_theme_changed = true;
4180 last_dark_mode_state = display_server->is_dark_mode();
4181 }
4182 }
4183
4184 if (use_system_accent_color) {
4185 if (display_server->get_accent_color() != last_system_accent_color) {
4186 system_theme_changed = true;
4187 last_system_accent_color = display_server->get_accent_color();
4188 }
4189 }
4190
4191 if (system_theme_changed) {
4192 EditorThemeManager::set_theme_outdated();
4193
4194 SceneTree *sml = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
4195 if (!sml) {
4196 return;
4197 }
4198 Node *root = sml->get_root()->get_child(0);
4199 if (!root) {
4200 return;
4201 }
4202 // Some theme related settings are updated in editor settings change handlers.
4203 // Using "NOTIFICATION_EDITOR_SETTINGS_CHANGED" to simulate manual theme change from the editor settings and ensure all parts of the editor are updated correctly.
4204 root->propagate_notification(EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED);
4205 } else if (menu_type == MENU_TYPE_GLOBAL && display_server->is_dark_mode_supported() && display_server->is_dark_mode() != last_dark_mode_state) {
4206 last_dark_mode_state = display_server->is_dark_mode();
4207
4208 // Update system menus.
4209 bool dark_mode = DisplayServer::get_singleton()->is_dark_mode();
4210
4211 _update_system_menu_icons(dark_mode);
4212
4213 editor_dock_manager->update_docks_menu();
4214 }
4215}
4216
4217void EditorNode::_tool_menu_option(int p_idx) {
4218 switch (tool_menu->get_item_id(p_idx)) {
4219 case TOOLS_ORPHAN_RESOURCES: {
4220 orphan_resources->show();
4221 } break;
4222 case TOOLS_BUILD_PROFILE_MANAGER: {
4223 build_profile_manager->popup_centered_clamped(Size2(700, 800) * EDSCALE, 0.8);
4224 } break;
4225 case TOOLS_PROJECT_UPGRADE: {
4226 project_upgrade_tool->popup_dialog();
4227 } break;
4228 case TOOLS_CLEAR_PROJECT_CACHE: {
4229 clear_cache_dialog->popup_centered();
4230 } break;
4231 case TOOLS_CUSTOM: {
4232 if (tool_menu->get_item_submenu(p_idx) == "") {
4233 Callable callback = tool_menu->get_item_metadata(p_idx);
4234 Callable::CallError ce;
4235 Variant result;
4236 callback.callp(nullptr, 0, result, ce);
4237
4238 if (ce.error != Callable::CallError::CALL_OK) {
4239 String err = Variant::get_callable_error_text(callback, nullptr, 0, ce);
4240 ERR_PRINT("Error calling function from tool menu: " + err);
4241 }
4242 } // Else it's a submenu so don't do anything.
4243 } break;
4244 }
4245}
4246
4247void EditorNode::_export_as_menu_option(int p_idx) {
4248 if (p_idx == 0) { // MeshLibrary
4249 current_menu_option = FILE_EXPORT_MESH_LIBRARY;
4250
4251 if (!editor_data.get_edited_scene_root()) {
4252 show_warning(TTR("This operation can't be done without a scene."));
4253 return;
4254 }
4255
4256 List<String> extensions;
4257 Ref<MeshLibrary> ml(memnew(MeshLibrary));
4258 ResourceSaver::get_recognized_extensions(ml, &extensions);
4259 file_export_lib->clear_filters();
4260 for (const String &E : extensions) {
4261 file_export_lib->add_filter("*." + E);
4262 }
4263
4264 file_export_lib->set_title(TTR("Export Mesh Library"));
4265 file_export_lib->popup_file_dialog();
4266 } else { // Custom menu options added by plugins
4267 if (export_as_menu->get_item_submenu(p_idx).is_empty()) { // If not a submenu
4268 Callable callback = export_as_menu->get_item_metadata(p_idx);
4269 Callable::CallError ce;
4270 Variant result;
4271 callback.callp(nullptr, 0, result, ce);
4272
4273 if (ce.error != Callable::CallError::CALL_OK) {
4274 String err = Variant::get_callable_error_text(callback, nullptr, 0, ce);
4275 ERR_PRINT("Error calling function from export_as menu: " + err);
4276 }
4277 }
4278 }
4279}
4280
4281int EditorNode::_next_unsaved_scene(bool p_valid_filename, int p_start) {
4282 for (int i = p_start; i < editor_data.get_edited_scene_count(); i++) {
4283 if (!editor_data.get_edited_scene_root(i)) {
4284 continue;
4285 }
4286
4287 String scene_filename = editor_data.get_edited_scene_root(i)->get_scene_file_path();
4288 if (p_valid_filename && scene_filename.is_empty()) {
4289 continue;
4290 }
4291
4292 bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(i));
4293 if (unsaved) {
4294 return i;
4295 } else {
4296 for (int j = 0; j < editor_data.get_editor_plugin_count(); j++) {
4297 if (!editor_data.get_editor_plugin(j)->get_unsaved_status(scene_filename).is_empty()) {
4298 return i;
4299 }
4300 }
4301 }
4302 }
4303 return -1;
4304}
4305
4306void EditorNode::_exit_editor(int p_exit_code) {
4307 exiting = true;
4308 waiting_for_first_scan = false;
4309 resource_preview->stop(); // Stop early to avoid crashes.
4310 _save_editor_layout();
4311
4312 // Dim the editor window while it's quitting to make it clearer that it's busy.
4313 dim_editor(true);
4314
4315 // Unload addons before quitting to allow cleanup.
4316 unload_editor_addons();
4317
4318 if (!files_to_delete_on_exit.is_empty()) {
4319 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
4320 for (const String &path : files_to_delete_on_exit) {
4321 if (da->file_exists(path) || da->dir_exists(path)) {
4322 OS::get_singleton()->move_to_trash(ProjectSettings::get_singleton()->globalize_path(path));
4323 }
4324 }
4325 }
4326 get_tree()->quit(p_exit_code);
4327}
4328
4329void EditorNode::unload_editor_addons() {
4330 for (const KeyValue<String, EditorPlugin *> &E : addon_name_to_plugin) {
4331 print_verbose(vformat("Unloading addon: %s", E.key));
4332 remove_editor_plugin(E.value, false);
4333 memdelete(E.value);
4334 }
4335
4336 addon_name_to_plugin.clear();
4337}
4338
4339void EditorNode::_discard_changes(const String &p_str) {
4340 switch (current_menu_option) {
4341 case SCENE_CLOSE:
4342 case SCENE_TAB_CLOSE: {
4343 const String path = editor_data.get_scene_path(tab_closing_idx);
4344 if (!path.is_empty()) {
4345 _update_prev_closed_scenes(path, true);
4346 }
4347
4348 // Don't close tabs when exiting the editor (required for "restore_scenes_on_load" setting).
4349 if (!_is_closing_editor()) {
4350 _remove_scene(tab_closing_idx);
4351 scene_tabs->update_scene_tabs();
4352 }
4353 _proceed_closing_scene_tabs();
4354 } break;
4355 case SCENE_RELOAD_SAVED_SCENE: {
4356 int cur_idx = editor_data.get_edited_scene();
4357 reload_scene(editor_data.get_scene_path(cur_idx));
4358 confirmation->hide();
4359 } break;
4360 case SCENE_QUIT: {
4361 project_run_bar->stop_playing();
4362 _exit_editor(EXIT_SUCCESS);
4363
4364 } break;
4365 case PROJECT_QUIT_TO_PROJECT_MANAGER: {
4366 _restart_editor(true);
4367 } break;
4368 case PROJECT_RELOAD_CURRENT_PROJECT: {
4369 _restart_editor();
4370 } break;
4371 case TOOLS_CLEAR_PROJECT_CACHE: {
4372 files_to_delete_on_exit = LocalVector<String>{
4373 "res://.godot/imported",
4374 "res://.godot/exported",
4375 "res://.godot/mono",
4376 "res://.godot/extension_list.cfg",
4377 "res://.godot/global_script_class_cache.cfg",
4378 "res://.godot/scene_groups_cache.cfg",
4379 "res://.godot/uid_cache.bin",
4380 "res://.godot/editor/editor_script_doc_cache.res",
4381 "res://.godot/editor/" + EditorFileSystem::CACHE_FILE_NAME,
4382 "res://.godot/editor/filesystem_update4",
4383 };
4384 _restart_editor(false);
4385 } break;
4386 }
4387}
4388
4389void EditorNode::_update_file_menu_opened() {
4390 bool has_unsaved = false;
4391 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
4392 if (is_scene_unsaved(i)) {
4393 has_unsaved = true;
4394 break;
4395 }
4396 }
4397 if (has_unsaved) {
4398 file_menu->set_item_disabled(file_menu->get_item_index(SCENE_SAVE_ALL_SCENES), false);
4399 file_menu->set_item_tooltip(file_menu->get_item_index(SCENE_SAVE_ALL_SCENES), String());
4400 } else {
4401 file_menu->set_item_disabled(file_menu->get_item_index(SCENE_SAVE_ALL_SCENES), true);
4402 file_menu->set_item_tooltip(file_menu->get_item_index(SCENE_SAVE_ALL_SCENES), TTR("All scenes are already saved."));
4403 }
4404 _update_undo_redo_allowed();
4405}
4406
4407void EditorNode::_palette_quick_open_dialog() {
4408 quick_open_color_palette->popup_dialog({ "ColorPalette" }, palette_file_selected_callback);
4409 quick_open_color_palette->set_title(TTRC("Quick Open Color Palette..."));
4410}
4411
4412void EditorNode::_clear_cache_confirmed() {
4413 _menu_option_confirm(TOOLS_CLEAR_PROJECT_CACHE, false);
4414}
4415
4416void EditorNode::replace_resources_in_object(Object *p_object, const Vector<Ref<Resource>> &p_source_resources, const Vector<Ref<Resource>> &p_target_resource) {
4417 List<PropertyInfo> pi;
4418 p_object->get_property_list(&pi);
4419
4420 for (const PropertyInfo &E : pi) {
4421 if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
4422 continue;
4423 }
4424
4425 switch (E.type) {
4426 case Variant::OBJECT: {
4427 if (E.hint == PROPERTY_HINT_RESOURCE_TYPE) {
4428 const Variant &v = p_object->get(E.name);
4429 Ref<Resource> res = v;
4430
4431 if (res.is_valid()) {
4432 int res_idx = p_source_resources.find(res);
4433 if (res_idx != -1) {
4434 p_object->set(E.name, p_target_resource.get(res_idx));
4435 } else {
4436 replace_resources_in_object(v, p_source_resources, p_target_resource);
4437 }
4438 }
4439 }
4440 } break;
4441 case Variant::ARRAY: {
4442 Array varray = p_object->get(E.name);
4443 int len = varray.size();
4444 bool array_requires_updating = false;
4445 for (int i = 0; i < len; i++) {
4446 const Variant &v = varray.get(i);
4447 Ref<Resource> res = v;
4448
4449 if (res.is_valid()) {
4450 int res_idx = p_source_resources.find(res);
4451 if (res_idx != -1) {
4452 varray.set(i, p_target_resource.get(res_idx));
4453 array_requires_updating = true;
4454 } else {
4455 replace_resources_in_object(v, p_source_resources, p_target_resource);
4456 }
4457 }
4458 }
4459 if (array_requires_updating) {
4460 p_object->set(E.name, varray);
4461 }
4462 } break;
4463 case Variant::DICTIONARY: {
4464 Dictionary d = p_object->get(E.name);
4465 bool dictionary_requires_updating = false;
4466 for (const Variant &F : d.get_key_list()) {
4467 Variant v = d[F];
4468 Ref<Resource> res = v;
4469
4470 if (res.is_valid()) {
4471 int res_idx = p_source_resources.find(res);
4472 if (res_idx != -1) {
4473 d[F] = p_target_resource.get(res_idx);
4474 dictionary_requires_updating = true;
4475 } else {
4476 replace_resources_in_object(v, p_source_resources, p_target_resource);
4477 }
4478 }
4479 }
4480 if (dictionary_requires_updating) {
4481 p_object->set(E.name, d);
4482 }
4483 } break;
4484 default: {
4485 }
4486 }
4487 }
4488
4489 Node *n = Object::cast_to<Node>(p_object);
4490 if (n) {
4491 for (int i = 0; i < n->get_child_count(); i++) {
4492 replace_resources_in_object(n->get_child(i), p_source_resources, p_target_resource);
4493 }
4494 }
4495}
4496
4497void EditorNode::replace_resources_in_scenes(const Vector<Ref<Resource>> &p_source_resources, const Vector<Ref<Resource>> &p_target_resource) {
4498 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
4499 Node *edited_scene_root = editor_data.get_edited_scene_root(i);
4500 if (edited_scene_root) {
4501 replace_resources_in_object(edited_scene_root, p_source_resources, p_target_resource);
4502 }
4503 }
4504}
4505
4506void EditorNode::add_editor_plugin(EditorPlugin *p_editor, bool p_config_changed) {
4507#ifndef DISABLE_DEPRECATED
4508 if (p_editor->has_main_screen()) {
4509 singleton->editor_main_screen->add_main_plugin(p_editor);
4510 }
4511#endif
4512 singleton->editor_data.add_editor_plugin(p_editor);
4513 singleton->add_child(p_editor);
4514 if (p_config_changed) {
4515 p_editor->enable_plugin();
4516 }
4517}
4518
4519void EditorNode::remove_editor_plugin(EditorPlugin *p_editor, bool p_config_changed) {
4520#ifndef DISABLE_DEPRECATED
4521 if (p_editor->has_main_screen()) {
4522 singleton->editor_main_screen->remove_main_plugin(p_editor);
4523 }
4524#endif
4525 p_editor->make_visible(false);
4526 p_editor->clear();
4527 if (p_config_changed) {
4528 p_editor->disable_plugin();
4529 }
4530 singleton->editor_plugins_over->remove_plugin(p_editor);
4531 singleton->editor_plugins_force_over->remove_plugin(p_editor);
4532 singleton->editor_plugins_force_input_forwarding->remove_plugin(p_editor);
4533 singleton->remove_child(p_editor);
4534 singleton->editor_data.remove_editor_plugin(p_editor);
4535
4536 for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : singleton->active_plugins) {
4537 kv.value.erase(p_editor);
4538 }
4539}
4540
4541void EditorNode::add_extension_editor_plugin(const StringName &p_class_name) {
4542 ERR_FAIL_COND_MSG(!ClassDB::class_exists(p_class_name), vformat("No such editor plugin registered: %s", p_class_name));
4543 ERR_FAIL_COND_MSG(!ClassDB::is_parent_class(p_class_name, SNAME("EditorPlugin")), vformat("Class is not an editor plugin: %s", p_class_name));
4544 ERR_FAIL_COND_MSG(singleton->editor_data.has_extension_editor_plugin(p_class_name), vformat("Editor plugin already added for class: %s", p_class_name));
4545
4546 EditorPlugin *plugin = Object::cast_to<EditorPlugin>(ClassDB::_instantiate_allow_unexposed(p_class_name));
4547 singleton->editor_data.add_extension_editor_plugin(p_class_name, plugin);
4548 add_editor_plugin(plugin);
4549}
4550
4551void EditorNode::remove_extension_editor_plugin(const StringName &p_class_name) {
4552 // If we're exiting, the editor plugins will get cleaned up anyway, so don't do anything.
4553 if (!singleton || singleton->exiting) {
4554 return;
4555 }
4556
4557 ERR_FAIL_COND_MSG(!singleton->editor_data.has_extension_editor_plugin(p_class_name), vformat("No editor plugin added for class: %s", p_class_name));
4558
4559 EditorPlugin *plugin = singleton->editor_data.get_extension_editor_plugin(p_class_name);
4560 remove_editor_plugin(plugin);
4561 memdelete(plugin);
4562 singleton->editor_data.remove_extension_editor_plugin(p_class_name);
4563}
4564
4565void EditorNode::_update_addon_config() {
4566 if (_initializing_plugins) {
4567 return;
4568 }
4569
4570 Vector<String> enabled_addons;
4571
4572 for (const KeyValue<String, EditorPlugin *> &E : addon_name_to_plugin) {
4573 enabled_addons.push_back(E.key);
4574 }
4575
4576 if (enabled_addons.is_empty()) {
4577 ProjectSettings::get_singleton()->set("editor_plugins/enabled", Variant());
4578 } else {
4579 enabled_addons.sort();
4580 ProjectSettings::get_singleton()->set("editor_plugins/enabled", enabled_addons);
4581 }
4582
4583 project_settings_editor->queue_save();
4584}
4585
4586void EditorNode::set_addon_plugin_enabled(const String &p_addon, bool p_enabled, bool p_config_changed) {
4587 String addon_path = p_addon;
4588
4589 if (!addon_path.begins_with("res://")) {
4590 addon_path = "res://addons/" + addon_path + "/plugin.cfg";
4591 }
4592
4593 ERR_FAIL_COND(p_enabled && addon_name_to_plugin.has(addon_path));
4594 ERR_FAIL_COND(!p_enabled && !addon_name_to_plugin.has(addon_path));
4595
4596 if (!p_enabled) {
4597 EditorPlugin *addon = addon_name_to_plugin[addon_path];
4598 remove_editor_plugin(addon, p_config_changed);
4599 memdelete(addon);
4600 addon_name_to_plugin.erase(addon_path);
4601 _update_addon_config();
4602 return;
4603 }
4604
4605 Ref<ConfigFile> cf;
4606 cf.instantiate();
4607 if (!DirAccess::exists(addon_path.get_base_dir())) {
4608 _remove_plugin_from_enabled(addon_path);
4609 WARN_PRINT("Addon '" + addon_path + "' failed to load. No directory found. Removing from enabled plugins.");
4610 return;
4611 }
4612 Error err = cf->load(addon_path);
4613 if (err != OK) {
4614 show_warning(vformat(TTR("Unable to enable addon plugin at: '%s' parsing of config failed."), addon_path));
4615 return;
4616 }
4617
4618 String plugin_version;
4619 if (cf->has_section_key("plugin", "version")) {
4620 plugin_version = cf->get_value("plugin", "version");
4621 }
4622
4623 if (!cf->has_section_key("plugin", "script")) {
4624 show_warning(vformat(TTR("Unable to find script field for addon plugin at: '%s'."), addon_path));
4625 return;
4626 }
4627
4628 String script_path = cf->get_value("plugin", "script");
4629 Ref<Script> scr; // We need to save it for creating "ep" below.
4630
4631 // Only try to load the script if it has a name. Else, the plugin has no init script.
4632 EditorPlugin *ep = nullptr;
4633 if (script_path.length() > 0) {
4634 script_path = addon_path.get_base_dir().path_join(script_path);
4635 // We should not use the cached version on startup to prevent a script reload
4636 // if it is already loaded and potentially running from autoloads. See GH-100750.
4637 scr = ResourceLoader::load(script_path, "Script", EditorFileSystem::get_singleton()->doing_first_scan() ? ResourceFormatLoader::CACHE_MODE_REUSE : ResourceFormatLoader::CACHE_MODE_IGNORE);
4638
4639 if (scr.is_null()) {
4640 show_warning(vformat(TTR("Unable to load addon script from path: '%s'."), script_path));
4641 return;
4642 }
4643
4644 // Errors in the script cause the base_type to be an empty StringName.
4645 if (scr->get_instance_base_type() == StringName()) {
4646 if (_initializing_plugins) {
4647 // However, if it happens during initialization, waiting for file scan might help.
4648 pending_addons.push_back(p_addon);
4649 return;
4650 }
4651
4652 show_warning(vformat(TTR("Unable to load addon script from path: '%s'. This might be due to a code error in that script.\nDisabling the addon at '%s' to prevent further errors."), script_path, addon_path));
4653 _remove_plugin_from_enabled(addon_path);
4654 return;
4655 }
4656
4657 // Plugin init scripts must inherit from EditorPlugin and be tools.
4658 if (!ClassDB::is_parent_class(scr->get_instance_base_type(), "EditorPlugin")) {
4659 show_warning(vformat(TTR("Unable to load addon script from path: '%s'. Base type is not 'EditorPlugin'."), script_path));
4660 return;
4661 }
4662
4663 if (!scr->is_tool()) {
4664 show_warning(vformat(TTR("Unable to load addon script from path: '%s'. Script is not in tool mode."), script_path));
4665 return;
4666 }
4667
4668 Object *obj = ClassDB::instantiate(scr->get_instance_base_type());
4669 ep = Object::cast_to<EditorPlugin>(obj);
4670 ERR_FAIL_NULL(ep);
4671 ep->set_script(scr);
4672 } else {
4673 ep = memnew(EditorPlugin);
4674 }
4675
4676 ep->set_plugin_version(plugin_version);
4677 addon_name_to_plugin[addon_path] = ep;
4678 add_editor_plugin(ep, p_config_changed);
4679
4680 _update_addon_config();
4681}
4682
4683bool EditorNode::is_addon_plugin_enabled(const String &p_addon) const {
4684 if (p_addon.begins_with("res://")) {
4685 return addon_name_to_plugin.has(p_addon);
4686 }
4687
4688 return addon_name_to_plugin.has("res://addons/" + p_addon + "/plugin.cfg");
4689}
4690
4691void EditorNode::_remove_edited_scene(bool p_change_tab) {
4692 // When scene gets closed no node is edited anymore, so make sure the editors are notified before nodes are freed.
4693 hide_unused_editors(SceneTreeDock::get_singleton());
4694 editor_selection->clear();
4695 editor_selection->update(false);
4696
4697 int new_index = editor_data.get_edited_scene();
4698 int old_index = new_index;
4699
4700 if (new_index > 0) {
4701 new_index = new_index - 1;
4702 } else if (editor_data.get_edited_scene_count() > 1) {
4703 new_index = 1;
4704 } else {
4705 editor_data.add_edited_scene(-1);
4706 new_index = 1;
4707 }
4708
4709 if (p_change_tab) {
4710 _set_current_scene(new_index);
4711 }
4712 editor_data.remove_scene(old_index);
4713 _update_title();
4714 scene_tabs->update_scene_tabs();
4715}
4716
4717void EditorNode::_remove_scene(int p_idx, bool p_change_tab) {
4718 // Clear icon cache in case some scripts are no longer needed or class icons are outdated.
4719 // FIXME: Ideally the cache should never be cleared and only updated on per-script basis, when an icon changes.
4720 editor_data.clear_script_icon_cache();
4721 class_icon_cache.clear();
4722
4723 _save_editor_states(editor_data.get_scene_path(p_idx), p_idx);
4724 if (editor_data.get_edited_scene() == p_idx) {
4725 // Scene to remove is current scene.
4726 _remove_edited_scene(p_change_tab);
4727 } else {
4728 // Scene to remove is not active scene.
4729 editor_data.remove_scene(p_idx);
4730 }
4731}
4732
4733void EditorNode::set_edited_scene(Node *p_scene) {
4734 set_edited_scene_root(p_scene, true);
4735}
4736
4737void EditorNode::set_edited_scene_root(Node *p_scene, bool p_auto_add) {
4738 Node *old_edited_scene_root = get_editor_data().get_edited_scene_root();
4739 ERR_FAIL_COND_MSG(p_scene && p_scene != old_edited_scene_root && p_scene->get_parent(), "Non-null nodes that are set as edited scene should not have a parent node.");
4740
4741 if (p_auto_add && old_edited_scene_root && old_edited_scene_root->get_parent() == scene_root) {
4742 scene_root->remove_child(old_edited_scene_root);
4743 }
4744 get_editor_data().set_edited_scene_root(p_scene);
4745
4746 if (Object::cast_to<Popup>(p_scene)) {
4747 Object::cast_to<Popup>(p_scene)->show();
4748 }
4749 SceneTreeDock::get_singleton()->set_edited_scene(p_scene);
4750 if (get_tree()) {
4751 get_tree()->set_edited_scene_root(p_scene);
4752 }
4753
4754 if (p_auto_add && p_scene) {
4755 scene_root->add_child(p_scene, true);
4756 }
4757}
4758
4759String EditorNode::get_preview_locale() const {
4760 const Ref<TranslationDomain> &main_domain = TranslationServer::get_singleton()->get_main_domain();
4761 return main_domain->is_enabled() ? main_domain->get_locale_override() : String();
4762}
4763
4764bool EditorNode::is_pseudolocalization_enabled() const {
4765 const Ref<TranslationDomain> &main_domain = TranslationServer::get_singleton()->get_main_domain();
4766 return main_domain->is_pseudolocalization_enabled();
4767}
4768
4769void EditorNode::set_preview_locale(const String &p_locale, bool p_pseudolocalization) {
4770 const String &prev_locale = get_preview_locale();
4771 bool prev_pseudo = is_pseudolocalization_enabled();
4772 if (prev_locale == p_locale && prev_pseudo == p_pseudolocalization) {
4773 return;
4774 }
4775
4776 // Texts set in the editor could be identifiers that should never be translated.
4777 // So we need to disable translation entirely.
4778 Ref<TranslationDomain> main_domain = TranslationServer::get_singleton()->get_main_domain();
4779 if (p_locale.is_empty()) {
4780 // Disable preview. Use the fallback locale.
4781 main_domain->set_locale_override(TranslationServer::get_singleton()->get_fallback_locale());
4782 } else {
4783 // Preview a specific locale.
4784 main_domain->set_locale_override(p_locale);
4785 }
4786 main_domain->set_pseudolocalization_enabled(p_pseudolocalization);
4787 // Texts set in the editor could be identifiers that should never be translated.
4788 // So we need to disable translation entirely.
4789 main_domain->set_enabled(p_pseudolocalization || !p_locale.is_empty());
4790
4791 EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "preview_locale", p_locale);
4792
4793 _translation_resources_changed();
4794}
4795
4796Dictionary EditorNode::_get_main_scene_state() {
4797 Dictionary state;
4798 state["scene_tree_offset"] = SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
4799 state["property_edit_offset"] = InspectorDock::get_inspector_singleton()->get_scroll_offset();
4800 state["node_filter"] = SceneTreeDock::get_singleton()->get_filter();
4801 return state;
4802}
4803
4804void EditorNode::_set_main_scene_state(const Dictionary &p_state) {
4805 if (p_state.has("scene_tree_offset")) {
4806 SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->set_value(p_state["scene_tree_offset"]);
4807 }
4808 if (p_state.has("property_edit_offset")) {
4809 InspectorDock::get_inspector_singleton()->set_scroll_offset(p_state["property_edit_offset"]);
4810 }
4811
4812 if (p_state.has("node_filter")) {
4813 SceneTreeDock::get_singleton()->set_filter(p_state["node_filter"]);
4814 }
4815
4816 // This should only happen at the very end.
4817
4818 EditorDebuggerNode::get_singleton()->update_live_edit_root();
4819 ScriptEditor::get_singleton()->set_scene_root_script(editor_data.get_scene_root_script(editor_data.get_edited_scene()));
4820 editor_data.notify_edited_scene_changed();
4821 emit_signal(SNAME("scene_changed"));
4822
4823 // Reset SDFGI after everything else so that any last-second scene modifications will be processed.
4824 RenderingServer::get_singleton()->sdfgi_reset();
4825}
4826
4827Ref<ConfigFile> EditorNode::_load_scene_config(const String &p_scene_path) {
4828 const String config_file_path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(p_scene_path.get_file() + "-editstate-" + p_scene_path.md5_text() + ".cfg");
4829
4830 Ref<ConfigFile> editor_state_cf;
4831 editor_state_cf.instantiate();
4832 editor_state_cf->load(config_file_path);
4833 return editor_state_cf;
4834}
4835
4836bool EditorNode::is_changing_scene() const {
4837 return changing_scene;
4838}
4839
4840void EditorNode::_set_current_scene(int p_idx) {
4841 if (p_idx == editor_data.get_edited_scene()) {
4842 return; // Pointless.
4843 }
4844
4845 _set_current_scene_nocheck(p_idx);
4846}
4847
4848void EditorNode::_set_current_scene_nocheck(int p_idx, bool p_ignore_state) {
4849 // Save the folding in case the scene gets reloaded.
4850 const String scene_path = editor_data.get_scene_path(p_idx);
4851 if (scene_path.is_empty() && editor_data.get_edited_scene_root(p_idx)) {
4852 editor_folding.save_scene_folding(editor_data.get_edited_scene_root(p_idx), editor_data.get_scene_path(p_idx));
4853 }
4854
4855 changing_scene = true;
4856 if (!p_ignore_state) {
4857 editor_data.save_edited_scene_state(editor_selection, &editor_history, _get_main_scene_state());
4858 }
4859
4860 Node *old_scene = get_editor_data().get_edited_scene_root();
4861
4862 editor_selection->clear();
4863 SceneTreeDock::get_singleton()->clear_previous_node_selection();
4864 editor_data.set_edited_scene(p_idx);
4865
4866 Node *new_scene = editor_data.get_edited_scene_root();
4867
4868 // Remove the scene only if it's a new scene, preventing performance issues when adding and removing scenes.
4869 if (old_scene && new_scene != old_scene && old_scene->get_parent() == scene_root) {
4870 scene_root->remove_child(old_scene);
4871 }
4872
4873 if (Popup *p = Object::cast_to<Popup>(new_scene)) {
4874 p->show();
4875 }
4876
4877 SceneTreeDock::get_singleton()->set_edited_scene(new_scene);
4878 if (get_tree()) {
4879 get_tree()->set_edited_scene_root(new_scene);
4880 }
4881
4882 if (new_scene && new_scene->get_parent() != scene_root) {
4883 scene_root->add_child(new_scene, true);
4884 }
4885
4886 if (editor_data.check_and_update_scene(p_idx)) {
4887 if (!editor_data.get_scene_path(p_idx).is_empty()) {
4888 editor_folding.load_scene_folding(editor_data.get_edited_scene_root(p_idx), scene_path);
4889 }
4890
4891 EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_scene_history_id(p_idx), false);
4892 }
4893 resource_count.clear();
4894 SceneTreeDock::get_singleton()->get_tree_editor()->update_tree();
4895
4896 _update_title();
4897
4898 const Dictionary state = editor_data.restore_edited_scene_state(editor_selection, &editor_history);
4899 _set_main_scene_state(state);
4900 _update_undo_redo_allowed();
4901 _update_unsaved_cache();
4902
4903 changing_scene = false;
4904
4905 if (EDITOR_GET("interface/scene_tabs/auto_select_current_scene_file")) {
4906 FileSystemDock::get_singleton()->navigate_to_path(scene_path);
4907 }
4908}
4909
4910void EditorNode::setup_built_in_resource(const Ref<Resource> &p_resource, const String &p_owner_path) {
4911 String resource_class;
4912 const Ref<MissingResource> &missing_resource = p_resource;
4913 if (missing_resource.is_valid()) {
4914 resource_class = missing_resource->get_original_class();
4915 } else {
4916 resource_class = p_resource->get_class();
4917 }
4918
4919 String unique_id;
4920 String final_path;
4921 while (true) {
4922 unique_id = resource_class + "_" + Resource::generate_scene_unique_id();
4923 final_path = p_owner_path + "::" + unique_id;
4924
4925 if (!ResourceCache::has(final_path)) {
4926 break;
4927 }
4928 }
4929 p_resource->set_scene_unique_id(unique_id);
4930 p_resource->set_path(final_path);
4931}
4932
4933void EditorNode::setup_color_picker(ColorPicker *p_picker) {
4934 p_picker->set_editor_settings(EditorSettings::get_singleton());
4935 int default_color_mode = EditorSettings::get_singleton()->get_project_metadata("color_picker", "color_mode", EDITOR_GET("interface/inspector/default_color_picker_mode"));
4936 int picker_shape = EditorSettings::get_singleton()->get_project_metadata("color_picker", "picker_shape", EDITOR_GET("interface/inspector/default_color_picker_shape"));
4937 bool show_intensity = EDITOR_GET("interface/inspector/color_picker_show_intensity");
4938
4939 p_picker->set_color_mode((ColorPicker::ColorModeType)default_color_mode);
4940 p_picker->set_picker_shape((ColorPicker::PickerShapeType)picker_shape);
4941 p_picker->set_edit_intensity(show_intensity);
4942
4943 p_picker->set_quick_open_callback(callable_mp(this, &EditorNode::_palette_quick_open_dialog));
4944 p_picker->set_palette_saved_callback(callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::update_file));
4945 palette_file_selected_callback = callable_mp(p_picker, &ColorPicker::_quick_open_palette_file_selected);
4946}
4947
4948void EditorNode::register_hdr_viewport(Viewport *p_viewport) {
4949 const bool hdr_requested = GLOBAL_GET("display/window/hdr/request_hdr_output");
4950 const bool hdr_2d_enabled = GLOBAL_GET("rendering/viewport/hdr_2d");
4951 p_viewport->set_use_hdr_2d(hdr_2d_enabled || hdr_requested);
4952
4953 hdr_viewports.push_back(p_viewport->get_instance_id());
4954}
4955
4956bool EditorNode::is_scene_open(const String &p_path) {
4957 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
4958 if (editor_data.get_scene_path(i) == p_path) {
4959 return true;
4960 }
4961 }
4962
4963 return false;
4964}
4965
4966bool EditorNode::is_multi_window_enabled() const {
4967 return !SceneTree::get_singleton()->get_root()->is_embedding_subwindows() && !EDITOR_GET("interface/editor/display/single_window_mode") && EDITOR_GET("interface/multi_window/enable");
4968}
4969
4970int EditorNode::new_scene() {
4971 int idx = editor_data.add_edited_scene(-1);
4972 _set_current_scene(idx); // Before trying to remove an empty scene, set the current tab index to the newly added tab index.
4973
4974 // Remove placeholder empty scene.
4975 if (editor_data.get_edited_scene_count() > 1) {
4976 for (int i = 0; i < editor_data.get_edited_scene_count() - 1; i++) {
4977 bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(i));
4978 if (!unsaved && editor_data.get_scene_path(i).is_empty() && editor_data.get_edited_scene_root(i) == nullptr) {
4979 editor_data.remove_scene(i);
4980 idx--;
4981 }
4982 }
4983 }
4984
4985 editor_data.clear_editor_states();
4986 scene_tabs->update_scene_tabs();
4987 return idx;
4988}
4989
4990Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_force_open_imported, bool p_update_tabs) {
4991 const String lpath = ProjectSettings::get_singleton()->localize_path(ResourceUID::ensure_path(p_scene));
4992 _update_prev_closed_scenes(lpath, false);
4993
4994 if (!p_set_inherited) {
4995 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
4996 if (editor_data.get_scene_path(i) == lpath) {
4997 // Already loaded, do nothing.
4998 return OK;
4999 }
5000 }
5001
5002 if (!p_force_open_imported && FileAccess::exists(lpath + ".import")) {
5003 open_imported->set_text(vformat(TTR("Scene '%s' was automatically imported, so it can't be modified.\nTo make changes to it, a new inherited scene can be created."), lpath.get_file()));
5004 open_imported->popup_centered();
5005 new_inherited_button->grab_focus();
5006 open_import_request = lpath;
5007 return OK;
5008 }
5009 }
5010
5011 if (!lpath.begins_with("res://")) {
5012 show_warning(TTR("Error loading scene, it must be inside the project path. Use 'Import' to open the scene, then save it inside the project path."));
5013 return ERR_FILE_NOT_FOUND;
5014 }
5015
5016 dependency_errors.clear();
5017
5018 Error err;
5019 Ref<PackedScene> sdata = ResourceLoader::load(lpath, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
5020
5021 if (!p_ignore_broken_deps && !dependency_errors.is_empty()) {
5022 current_menu_option = -1;
5023 dependency_error->show(lpath, dependency_errors);
5024 dependency_errors.clear();
5025 return ERR_FILE_MISSING_DEPENDENCIES;
5026 }
5027
5028 if (sdata.is_null()) {
5029 _dialog_display_load_error(lpath, err);
5030 return ERR_FILE_NOT_FOUND;
5031 }
5032
5033 dependency_errors.erase(lpath); // At least not self path.
5034
5035 for (KeyValue<String, HashSet<String>> &E : dependency_errors) {
5036 String txt = vformat(TTR("Scene '%s' has broken dependencies:"), E.key) + "\n";
5037 for (const String &F : E.value) {
5038 txt += "\t" + F + "\n";
5039 }
5040 add_io_error(txt);
5041 }
5042
5043 if (ResourceCache::has(lpath)) {
5044 // Used from somewhere else? No problem! Update state and replace sdata.
5045 Ref<PackedScene> ps = ResourceCache::get_ref(lpath);
5046 if (ps.is_valid()) {
5047 ps->replace_state(sdata->get_state());
5048 ps->set_last_modified_time(sdata->get_last_modified_time());
5049 sdata = ps;
5050 }
5051 } else {
5052 sdata->set_path(lpath, true); // Take over path.
5053 }
5054
5055 Node *new_scene = sdata->instantiate(p_set_inherited ? PackedScene::GEN_EDIT_STATE_MAIN_INHERITED : PackedScene::GEN_EDIT_STATE_MAIN);
5056 if (!new_scene) {
5057 sdata.unref();
5058 _dialog_display_load_error(lpath, ERR_FILE_CORRUPT);
5059 return ERR_FILE_CORRUPT;
5060 }
5061
5062 if (p_set_inherited) {
5063 Ref<SceneState> state = sdata->get_state();
5064 state->set_path(lpath);
5065 new_scene->set_scene_inherited_state(state);
5066 new_scene->set_scene_file_path(String());
5067 }
5068
5069 new_scene->set_scene_instance_state(Ref<SceneState>());
5070
5071 if (!restoring_scenes) {
5072 save_editor_layout_delayed();
5073 _add_to_recent_scenes(lpath);
5074 }
5075
5076 int idx = editor_data.get_edited_scene();
5077 if (idx == -1 || editor_data.get_edited_scene_root() || !editor_data.get_scene_path(idx).is_empty()) {
5078 idx = editor_data.add_edited_scene(-1);
5079 }
5080 editor_data.set_scene_root(idx, new_scene);
5081 editor_data.set_scene_resource(idx, sdata);
5082
5083 const Ref<ConfigFile> editor_state_cf = _load_scene_config(lpath);
5084 if (editor_state_cf->has_section("editor_states")) {
5085 editor_data.load_editor_plugin_states_from_config(editor_state_cf, idx);
5086 }
5087
5088 if (editor_folding.has_folding_data(lpath)) {
5089 editor_folding.load_scene_folding(new_scene, lpath);
5090 } else if (EDITOR_GET("interface/inspector/auto_unfold_foreign_scenes")) {
5091 editor_folding.unfold_scene(new_scene);
5092 editor_folding.save_scene_folding(new_scene, lpath);
5093 }
5094
5095 if (p_update_tabs) {
5096 scene_tabs->update_scene_tabs();
5097 }
5098 return OK;
5099}
5100
5101Error EditorNode::open_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_force_open_imported) {
5102 if (!is_inside_tree()) {
5103 defer_load_scene = p_scene;
5104 return OK;
5105 }
5106
5107 const String lpath = ProjectSettings::get_singleton()->localize_path(ResourceUID::ensure_path(p_scene));
5108 if (!p_set_inherited) {
5109 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
5110 if (editor_data.get_scene_path(i) == lpath) {
5111 _set_current_scene(i);
5112 scene_tabs->update_scene_tabs();
5113 return OK;
5114 }
5115 }
5116 }
5117
5118 bool ignore_state = !editor_data.get_edited_scene_root();
5119
5120 RETURN_IF_ERROR(load_scene(p_scene, p_ignore_broken_deps, p_set_inherited, p_force_open_imported));
5121
5122 int current_scene_idx = editor_data.get_edited_scene_count() - 1;
5123 Node *new_scene = editor_data.get_edited_scene_root(current_scene_idx);
5124 ERR_FAIL_NULL_V(new_scene, ERR_BUG);
5125
5126 _set_current_scene_nocheck(current_scene_idx, ignore_state);
5127
5128 // When editor plugins load in, they might use node transforms during their own setup, so make sure they're up to date.
5129 get_tree()->flush_transform_notifications();
5130
5131 EditorDebuggerNode::get_singleton()->update_live_edit_root();
5132
5133 if (restoring_scenes) {
5134 // Initialize history for restored scenes.
5135 ObjectID id = new_scene->get_instance_id();
5136 if (id != editor_history.get_current()) {
5137 editor_history.add_object(id);
5138 }
5139 }
5140
5141 if (p_set_inherited) {
5142 EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(editor_data.get_current_edited_scene_history_id());
5143 }
5144
5145 _update_title();
5146 return OK;
5147}
5148
5149HashMap<StringName, Variant> EditorNode::get_modified_properties_for_node(Node *p_node, bool p_node_references_only) {
5150 HashMap<StringName, Variant> modified_property_map;
5151
5152 List<PropertyInfo> pinfo;
5153 p_node->get_property_list(&pinfo);
5154 for (const PropertyInfo &E : pinfo) {
5155 if (E.usage & PROPERTY_USAGE_STORAGE) {
5156 bool node_reference = (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE);
5157 if (p_node_references_only && !node_reference) {
5158 continue;
5159 }
5160 bool is_valid_revert = false;
5161 Variant revert_value = EditorPropertyRevert::get_property_revert_value(p_node, E.name, &is_valid_revert);
5162 Variant current_value = p_node->get(E.name);
5163 if (is_valid_revert) {
5164 if (PropertyUtils::is_property_value_different(p_node, current_value, revert_value)) {
5165 // If this property is a direct node reference, save a NodePath instead to prevent corrupted references.
5166 if (node_reference) {
5167 Node *target_node = Object::cast_to<Node>(current_value);
5168 if (target_node) {
5169 modified_property_map[E.name] = p_node->get_path_to(target_node);
5170 }
5171 } else {
5172 modified_property_map[E.name] = current_value;
5173 }
5174 }
5175 }
5176 }
5177 }
5178
5179 return modified_property_map;
5180}
5181
5182HashMap<StringName, Variant> EditorNode::get_modified_properties_reference_to_nodes(Node *p_node, List<Node *> &p_nodes_referenced_by) {
5183 HashMap<StringName, Variant> modified_property_map;
5184
5185 List<PropertyInfo> pinfo;
5186 p_node->get_property_list(&pinfo);
5187 for (const PropertyInfo &E : pinfo) {
5188 if (E.usage & PROPERTY_USAGE_STORAGE) {
5189 if (E.type != Variant::OBJECT || E.hint != PROPERTY_HINT_NODE_TYPE) {
5190 continue;
5191 }
5192 Variant current_value = p_node->get(E.name);
5193 Node *target_node = Object::cast_to<Node>(current_value);
5194 if (target_node && p_nodes_referenced_by.find(target_node)) {
5195 modified_property_map[E.name] = p_node->get_path_to(target_node);
5196 }
5197 }
5198 }
5199
5200 return modified_property_map;
5201}
5202
5203void EditorNode::update_node_from_node_modification_entry(Node *p_node, ModificationNodeEntry &p_node_modification) {
5204 if (p_node) {
5205 // First, attempt to restore the script property since it may affect the get_property_list method.
5206 Variant *script_property_table_entry = p_node_modification.property_table.getptr(CoreStringName(script));
5207 if (script_property_table_entry) {
5208 p_node->set_script(*script_property_table_entry);
5209 }
5210
5211 // Get properties for this node.
5212 List<PropertyInfo> pinfo;
5213 p_node->get_property_list(&pinfo);
5214
5215 // Get names of all valid property names.
5216 HashMap<StringName, bool> property_node_reference_table;
5217 for (const PropertyInfo &E : pinfo) {
5218 if (E.usage & PROPERTY_USAGE_STORAGE) {
5219 if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) {
5220 property_node_reference_table[E.name] = true;
5221 } else {
5222 property_node_reference_table[E.name] = false;
5223 }
5224 }
5225 }
5226
5227 // Restore the modified properties for this node.
5228 for (const KeyValue<StringName, Variant> &E : p_node_modification.property_table) {
5229 bool *property_node_reference_table_entry = property_node_reference_table.getptr(E.key);
5230 if (property_node_reference_table_entry) {
5231 // If the property is a node reference, attempt to restore from the node path instead.
5232 bool is_node_reference = *property_node_reference_table_entry;
5233 if (is_node_reference) {
5234 if (E.value.get_type() == Variant::NODE_PATH) {
5235 p_node->set(E.key, p_node->get_node_or_null(E.value));
5236 }
5237 } else {
5238 p_node->set(E.key, E.value);
5239 }
5240 }
5241 }
5242
5243 // Restore the connections to other nodes.
5244 for (const ConnectionWithNodePath &E : p_node_modification.connections_to) {
5245 Connection conn = E.connection;
5246
5247 // Get the node the callable is targeting.
5248 Node *target_node = Object::cast_to<Node>(conn.callable.get_object());
5249
5250 // If the callable object no longer exists or is marked for deletion,
5251 // attempt to reaccquire the closest match by using the node path
5252 // we saved earlier.
5253 if (!target_node || !target_node->is_queued_for_deletion()) {
5254 target_node = p_node->get_node_or_null(E.node_path);
5255 }
5256
5257 if (target_node) {
5258 // Reconstruct the callable.
5259 Callable new_callable = Callable(target_node, conn.callable.get_method());
5260
5261 if (!p_node->is_connected(conn.signal.get_name(), new_callable)) {
5262 ERR_FAIL_COND(p_node->connect(conn.signal.get_name(), new_callable, conn.flags) != OK);
5263 }
5264 }
5265 }
5266
5267 // Restore the connections from other nodes.
5268 for (const Connection &E : p_node_modification.connections_from) {
5269 Connection conn = E;
5270
5271 bool valid = p_node->has_method(conn.callable.get_method()) || Ref<Script>(p_node->get_script()).is_null() || Ref<Script>(p_node->get_script())->has_method(conn.callable.get_method());
5272 ERR_CONTINUE_MSG(!valid, vformat("Attempt to connect signal '%s.%s' to nonexistent method '%s.%s'.", conn.signal.get_object()->get_class(), conn.signal.get_name(), conn.callable.get_object()->get_class(), conn.callable.get_method()));
5273
5274 // Get the object which the signal is connected from.
5275 Object *source_object = conn.signal.get_object();
5276
5277 if (source_object) {
5278 ERR_FAIL_COND(source_object->connect(conn.signal.get_name(), Callable(p_node, conn.callable.get_method()), conn.flags) != OK);
5279 }
5280 }
5281
5282 // Re-add the groups.
5283 for (const Node::GroupInfo &E : p_node_modification.groups) {
5284 p_node->add_to_group(E.name, E.persistent);
5285 }
5286 }
5287}
5288
5289bool EditorNode::is_additional_node_in_scene(Node *p_edited_scene, Node *p_reimported_root, Node *p_node) {
5290 if (p_node == p_reimported_root) {
5291 return false;
5292 }
5293
5294 bool node_part_of_subscene = p_node != p_edited_scene &&
5295 p_edited_scene->get_scene_inherited_state().is_valid() &&
5296 p_edited_scene->get_scene_inherited_state()->find_node_by_path(p_edited_scene->get_path_to(p_node)) >= 0 &&
5297 // It's important to process added nodes from the base scene in the inherited scene as
5298 // additional nodes to ensure they do not disappear on reload.
5299 // When p_reimported_root == p_edited_scene that means the edited scene
5300 // is the reimported scene, in that case the node is in the root base scene,
5301 // so it's not an addition, otherwise, the node would be added twice on reload.
5302 (p_node->get_owner() != p_edited_scene || p_reimported_root == p_edited_scene);
5303
5304 if (node_part_of_subscene) {
5305 return false;
5306 }
5307
5308 // Loop through the owners until either we reach the root node or nullptr
5309 Node *valid_node_owner = p_node->get_owner();
5310 while (valid_node_owner) {
5311 if (valid_node_owner == p_reimported_root) {
5312 break;
5313 }
5314 valid_node_owner = valid_node_owner->get_owner();
5315 }
5316
5317 // When the owner is the imported scene and the owner is also the edited scene,
5318 // that means the node was added in the current edited scene.
5319 // We can be sure here because if the node that the node does not come from
5320 // the base scene because we checked just over with 'get_scene_inherited_state()->find_node_by_path'.
5321 if (valid_node_owner == p_reimported_root && p_reimported_root != p_edited_scene) {
5322 return false;
5323 }
5324
5325 return true;
5326}
5327
5328void EditorNode::get_scene_editor_data_for_node(Node *p_root, Node *p_node, HashMap<NodePath, SceneEditorDataEntry> &p_table) {
5329 SceneEditorDataEntry new_entry;
5330 new_entry.is_display_folded = p_node->is_displayed_folded();
5331
5332 if (p_root != p_node) {
5333 new_entry.is_editable = p_root->is_editable_instance(p_node);
5334 }
5335
5336 p_table.insert(p_root->get_path_to(p_node), new_entry);
5337
5338 for (int i = 0; i < p_node->get_child_count(); i++) {
5339 get_scene_editor_data_for_node(p_root, p_node->get_child(i), p_table);
5340 }
5341}
5342
5343void EditorNode::get_preload_scene_modification_table(
5344 Node *p_edited_scene,
5345 Node *p_reimported_root,
5346 Node *p_node, InstanceModificationsEntry &p_instance_modifications) {
5347 if (is_additional_node_in_scene(p_edited_scene, p_reimported_root, p_node)) {
5348 // Only save additional nodes which have an owner since this was causing issues transient ownerless nodes
5349 // which get recreated upon scene tree entry.
5350 // For now instead, assume all ownerless nodes are transient and will have to be recreated.
5351 if (p_node->get_owner()) {
5352 HashMap<StringName, Variant> modified_properties = get_modified_properties_for_node(p_node, true);
5353 if (p_node->get_owner() == p_edited_scene) {
5354 AdditiveNodeEntry new_additive_node_entry;
5355 new_additive_node_entry.node = p_node;
5356 new_additive_node_entry.parent = p_reimported_root->get_path_to(p_node->get_parent());
5357 new_additive_node_entry.owner = p_node->get_owner();
5358 new_additive_node_entry.index = p_node->get_index();
5359
5360 CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_node);
5361 if (canvas_item) {
5362 new_additive_node_entry.transform_2d = canvas_item->get_transform();
5363 }
5364 Node3D *node_3d = Object::cast_to<Node3D>(p_node);
5365 if (node_3d) {
5366 new_additive_node_entry.transform_3d = node_3d->get_transform();
5367 }
5368
5369 p_instance_modifications.addition_list.push_back(new_additive_node_entry);
5370 }
5371 if (!modified_properties.is_empty()) {
5372 ModificationNodeEntry modification_node_entry;
5373 modification_node_entry.property_table = modified_properties;
5374
5375 p_instance_modifications.modifications[p_reimported_root->get_path_to(p_node)] = modification_node_entry;
5376 }
5377 }
5378 } else {
5379 HashMap<StringName, Variant> modified_properties = get_modified_properties_for_node(p_node, false);
5380
5381 // Find all valid connections to other nodes.
5382 List<Connection> connections_to;
5383 p_node->get_all_signal_connections(&connections_to);
5384
5385 List<ConnectionWithNodePath> valid_connections_to;
5386 for (const Connection &c : connections_to) {
5387 Node *connection_target_node = Object::cast_to<Node>(c.callable.get_object());
5388 if (connection_target_node) {
5389 // TODO: add support for reinstating custom callables
5390 if (!c.callable.is_custom()) {
5391 ConnectionWithNodePath connection_to;
5392 connection_to.connection = c;
5393 connection_to.node_path = p_node->get_path_to(connection_target_node);
5394 valid_connections_to.push_back(connection_to);
5395 }
5396 }
5397 }
5398
5399 // Find all valid connections from other nodes.
5400 List<Connection> connections_from;
5401 p_node->get_signals_connected_to_this(&connections_from);
5402
5403 List<Connection> valid_connections_from;
5404 for (const Connection &c : connections_from) {
5405 Node *source_node = Object::cast_to<Node>(c.signal.get_object());
5406
5407 Node *valid_source_owner = nullptr;
5408 if (source_node) {
5409 valid_source_owner = source_node->get_owner();
5410 while (valid_source_owner) {
5411 if (valid_source_owner == p_reimported_root) {
5412 break;
5413 }
5414 valid_source_owner = valid_source_owner->get_owner();
5415 }
5416 }
5417
5418 if (!source_node || valid_source_owner == nullptr) {
5419 // TODO: add support for reinstating custom callables
5420 if (!c.callable.is_custom()) {
5421 valid_connections_from.push_back(c);
5422 }
5423 }
5424 }
5425
5426 // Find all node groups.
5427 List<Node::GroupInfo> groups;
5428 p_node->get_groups(&groups);
5429
5430 if (!modified_properties.is_empty() || !valid_connections_to.is_empty() || !valid_connections_from.is_empty() || !groups.is_empty()) {
5431 ModificationNodeEntry modification_node_entry;
5432 modification_node_entry.property_table = modified_properties;
5433 modification_node_entry.connections_to = valid_connections_to;
5434 modification_node_entry.connections_from = valid_connections_from;
5435 modification_node_entry.groups = groups;
5436
5437 p_instance_modifications.modifications[p_reimported_root->get_path_to(p_node)] = modification_node_entry;
5438 }
5439 }
5440
5441 for (int i = 0; i < p_node->get_child_count(); i++) {
5442 get_preload_scene_modification_table(p_edited_scene, p_reimported_root, p_node->get_child(i), p_instance_modifications);
5443 }
5444}
5445
5446void EditorNode::get_preload_modifications_reference_to_nodes(
5447 Node *p_root,
5448 Node *p_node,
5449 HashSet<Node *> &p_excluded_nodes,
5450 List<Node *> &p_instance_list_with_children,
5451 HashMap<NodePath, ModificationNodeEntry> &p_modification_table) {
5452 if (!p_excluded_nodes.find(p_node)) {
5453 HashMap<StringName, Variant> modified_properties = get_modified_properties_reference_to_nodes(p_node, p_instance_list_with_children);
5454
5455 if (!modified_properties.is_empty()) {
5456 ModificationNodeEntry modification_node_entry;
5457 modification_node_entry.property_table = modified_properties;
5458
5459 p_modification_table[p_root->get_path_to(p_node)] = modification_node_entry;
5460 }
5461
5462 for (int i = 0; i < p_node->get_child_count(); i++) {
5463 get_preload_modifications_reference_to_nodes(p_root, p_node->get_child(i), p_excluded_nodes, p_instance_list_with_children, p_modification_table);
5464 }
5465 }
5466}
5467
5468void EditorNode::get_children_nodes(Node *p_node, List<Node *> &p_nodes) {
5469 for (int i = 0; i < p_node->get_child_count(); i++) {
5470 Node *child = p_node->get_child(i);
5471 p_nodes.push_back(child);
5472 get_children_nodes(child, p_nodes);
5473 }
5474}
5475
5476void EditorNode::replace_history_reimported_nodes(Node *p_original_root_node, Node *p_new_root_node, Node *p_node) {
5477 NodePath scene_path_to_node = p_original_root_node->get_path_to(p_node);
5478 Node *new_node = p_new_root_node->get_node_or_null(scene_path_to_node);
5479 if (new_node) {
5480 editor_history.replace_object(p_node->get_instance_id(), new_node->get_instance_id());
5481 } else {
5482 editor_history.replace_object(p_node->get_instance_id(), ObjectID());
5483 }
5484
5485 for (int i = 0; i < p_node->get_child_count(); i++) {
5486 replace_history_reimported_nodes(p_original_root_node, p_new_root_node, p_node->get_child(i));
5487 }
5488}
5489
5490bool EditorNode::has_previous_closed_scenes() const {
5491 return !prev_closed_scenes.is_empty();
5492}
5493
5494void EditorNode::edit_foreign_resource(Ref<Resource> p_resource) {
5495 open_scene(p_resource->get_path().get_slice("::", 0));
5496 callable_mp(InspectorDock::get_singleton(), &InspectorDock::edit_resource).call_deferred(p_resource);
5497}
5498
5499bool EditorNode::is_resource_read_only(Ref<Resource> p_resource, bool p_foreign_resources_are_writable) {
5500 ERR_FAIL_COND_V(p_resource.is_null(), false);
5501
5502 String path = p_resource->get_path();
5503 if (!path.is_resource_file()) {
5504 // If the resource name contains '::', that means it is a subresource embedded in another resource.
5505 int srpos = path.find("::");
5506 if (srpos != -1) {
5507 String base = path.substr(0, srpos);
5508 // If the base resource is a packed scene, we treat it as read-only if it is not the currently edited scene.
5509 if (ResourceLoader::get_resource_type(base) == "PackedScene") {
5510 if (!get_tree()->get_edited_scene_root() || get_tree()->get_edited_scene_root()->get_scene_file_path() != base) {
5511 // If we have not flagged foreign resources as writable or the base scene the resource is
5512 // part was imported, it can be considered read-only.
5513 if (!p_foreign_resources_are_writable || FileAccess::exists(base + ".import")) {
5514 return true;
5515 }
5516 }
5517 } else {
5518 // If a corresponding .import file exists for the base file, we assume it to be imported and should therefore treated as read-only.
5519 if (FileAccess::exists(base + ".import")) {
5520 return true;
5521 }
5522 }
5523 }
5524 } else if (FileAccess::exists(path + ".import")) {
5525 // The resource is not a subresource, but if it has an .import file, it's imported so treat it as read only.
5526 return true;
5527 }
5528
5529 return false;
5530}
5531
5532void EditorNode::request_instantiate_scene(const String &p_path) {
5533 SceneTreeDock::get_singleton()->instantiate(p_path);
5534}
5535
5536void EditorNode::request_instantiate_scenes(const Vector<String> &p_files) {
5537 SceneTreeDock::get_singleton()->instantiate_scenes(p_files);
5538}
5539
5540String EditorNode::get_multiwindow_support_tooltip_text() const {
5541 if (SceneTree::get_singleton()->get_root()->is_embedding_subwindows()) {
5542 if (DisplayServer::get_singleton()->has_feature(DisplayServerEnums::FEATURE_SUBWINDOWS)) {
5543 return TTR("Multi-window support is not available because the `--single-window` command line argument was used to start the editor.");
5544 } else {
5545 return TTR("Multi-window support is not available because the current platform doesn't support multiple windows.");
5546 }
5547 } else if (EDITOR_GET("interface/editor/display/single_window_mode")) {
5548 return TTR("Multi-window support is not available because Interface > Editor > Single Window Mode is enabled in the editor settings.");
5549 }
5550
5551 return TTR("Multi-window support is not available because Interface > Multi Window > Enable is disabled in the editor settings.");
5552}
5553
5554void EditorNode::_inherit_request(String p_file) {
5555 current_menu_option = SCENE_NEW_INHERITED_SCENE;
5556 _dialog_action(p_file);
5557}
5558
5559void EditorNode::_instantiate_request(const Vector<String> &p_files) {
5560 request_instantiate_scenes(p_files);
5561}
5562
5563void EditorNode::_close_messages() {
5564 old_split_ofs = center_split->get_split_offset();
5565 center_split->set_split_offset(0);
5566}
5567
5568void EditorNode::_show_messages() {
5569 center_split->set_split_offset(old_split_ofs);
5570}
5571
5572void EditorNode::_update_prev_closed_scenes(const String &p_scene_path, bool p_add_scene) {
5573 if (!p_scene_path.is_empty()) {
5574 const String scene_uid = ResourceUID::path_to_uid(p_scene_path);
5575 if (p_add_scene) {
5576 prev_closed_scenes.push_back(scene_uid);
5577 } else {
5578 prev_closed_scenes.erase(scene_uid);
5579 }
5580 file_menu->set_item_disabled(file_menu->get_item_index(SCENE_OPEN_PREV), prev_closed_scenes.is_empty());
5581 }
5582}
5583
5584void EditorNode::_add_to_recent_scenes(const String &p_scene) {
5585 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
5586 const String scene_uid = ResourceUID::path_to_uid(p_scene);
5587
5588#ifndef DISABLE_DEPRECATED
5589 if (rc.has(p_scene)) {
5590 rc.erase(p_scene);
5591 }
5592#endif
5593 if (rc.has(scene_uid)) {
5594 rc.erase(scene_uid);
5595 }
5596 rc.push_front(scene_uid);
5597 if (rc.size() > 10) {
5598 rc.resize(10);
5599 }
5600
5601 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", rc);
5602}
5603
5604void EditorNode::_open_recent_scene(int p_idx) {
5605 if (p_idx == recent_scenes->get_item_count() - 1) {
5606 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", Array());
5607 } else {
5608 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
5609 ERR_FAIL_INDEX(p_idx, rc.size());
5610
5611 if (open_scene(rc[p_idx]) != OK) {
5612 rc.remove_at(p_idx);
5613 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", rc);
5614 }
5615 }
5616}
5617
5618void EditorNode::_update_recent_scenes() {
5619 Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
5620 recent_scenes->clear();
5621
5622 LocalVector<int> missing_scenes;
5623 if (rc.size() == 0) {
5624 recent_scenes->add_item(TTRC("No Recent Scenes"), -1);
5625 recent_scenes->set_item_disabled(-1, true);
5626 } else {
5627 for (int i = 0; i < rc.size(); i++) {
5628 const String path = ResourceUID::ensure_path_nocheck(rc[i]);
5629 if (!path.is_empty() && ResourceLoader::exists(path)) {
5630 recent_scenes->add_item(path.trim_prefix("res://"), i);
5631 } else {
5632 missing_scenes.push_back(i);
5633 }
5634 }
5635
5636 recent_scenes->add_separator();
5637 recent_scenes->add_shortcut(ED_SHORTCUT("editor/clear_recent", TTRC("Clear Recent Scenes")));
5638
5639 if (!missing_scenes.is_empty()) {
5640 // Some scenes are missing, so update the stored list.
5641 Array new_scenes;
5642 for (int i = 0; i < rc.size(); i++) {
5643 if (!missing_scenes.has(i)) {
5644 new_scenes.push_back(rc[i]);
5645 }
5646 }
5647 EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", new_scenes);
5648 }
5649 }
5650 recent_scenes->set_item_auto_translate_mode(-1, AUTO_TRANSLATE_MODE_ALWAYS);
5651 recent_scenes->reset_size();
5652}
5653
5654void EditorNode::_quick_opened(const String &p_file_path) {
5655 load_scene_or_resource(p_file_path);
5656}
5657
5658void EditorNode::_project_run_started() {
5659 if (bool(EDITOR_GET("run/output/always_clear_output_on_play"))) {
5660 log->clear();
5661 }
5662
5663 int action_on_play = EDITOR_GET("run/bottom_panel/action_on_play");
5664 if (action_on_play == ACTION_ON_PLAY_OPEN_OUTPUT) {
5665 editor_dock_manager->open_dock(log, true);
5666 } else if (action_on_play == ACTION_ON_PLAY_OPEN_DEBUGGER) {
5667 editor_dock_manager->open_dock(EditorDebuggerNode::get_singleton(), true);
5668 }
5669}
5670
5671void EditorNode::_project_run_stopped() {
5672 int action_on_stop = EDITOR_GET("run/bottom_panel/action_on_stop");
5673 if (action_on_stop == ACTION_ON_STOP_CLOSE_BUTTOM_PANEL) {
5674 bottom_panel->hide_bottom_panel();
5675 }
5676}
5677
5678void EditorNode::notify_all_debug_sessions_exited() {
5679 project_run_bar->stop_playing();
5680}
5681
5682void EditorNode::add_io_error(const String &p_error) {
5683 DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
5684 singleton->load_errors->add_image(singleton->theme->get_icon(SNAME("Error"), EditorStringName(EditorIcons)));
5685 singleton->load_errors->add_text(p_error + "\n");
5686 // When a progress dialog is displayed, we will wait for it ot close before displaying
5687 // the io errors to prevent the io popup to set it's parent to the progress dialog.
5688 if (singleton->progress_dialog->is_visible()) {
5689 singleton->load_errors_queued_to_display = true;
5690 } else {
5691 EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
5692 }
5693}
5694
5695void EditorNode::add_io_warning(const String &p_warning) {
5696 DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
5697 singleton->load_errors->add_image(singleton->theme->get_icon(SNAME("Warning"), EditorStringName(EditorIcons)));
5698 singleton->load_errors->add_text(p_warning + "\n");
5699 // When a progress dialog is displayed, we will wait for it ot close before displaying
5700 // the io errors to prevent the io popup to set it's parent to the progress dialog.
5701 if (singleton->progress_dialog->is_visible()) {
5702 singleton->load_errors_queued_to_display = true;
5703 } else {
5704 EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
5705 }
5706}
5707
5708bool EditorNode::find_recursive_resources(const Variant &p_variant, HashSet<Resource *> &r_resources_found) {
5709 switch (p_variant.get_type()) {
5710 case Variant::ARRAY: {
5711 Array a = p_variant;
5712 for (int i = 0; i < a.size(); i++) {
5713 Variant v2 = a[i];
5714 if (v2.get_type() != Variant::ARRAY && v2.get_type() != Variant::DICTIONARY && v2.get_type() != Variant::OBJECT) {
5715 continue;
5716 }
5717 if (find_recursive_resources(v2, r_resources_found)) {
5718 return true;
5719 }
5720 }
5721 } break;
5722 case Variant::DICTIONARY: {
5723 Dictionary d = p_variant;
5724 for (const KeyValue<Variant, Variant> &kv : d) {
5725 const Variant &k = kv.key;
5726 const Variant &v2 = kv.value;
5727 if (k.get_type() == Variant::ARRAY || k.get_type() == Variant::DICTIONARY || k.get_type() == Variant::OBJECT) {
5728 if (find_recursive_resources(k, r_resources_found)) {
5729 return true;
5730 }
5731 }
5732 if (v2.get_type() == Variant::ARRAY || v2.get_type() == Variant::DICTIONARY || v2.get_type() == Variant::OBJECT) {
5733 if (find_recursive_resources(v2, r_resources_found)) {
5734 return true;
5735 }
5736 }
5737 }
5738 } break;
5739 case Variant::OBJECT: {
5740 Ref<Resource> r = p_variant;
5741
5742 if (r.is_null()) {
5743 return false;
5744 }
5745
5746 if (r_resources_found.has(r.ptr())) {
5747 return true;
5748 }
5749
5750 r_resources_found.insert(r.ptr());
5751
5752 List<PropertyInfo> plist;
5753 r->get_property_list(&plist);
5754 for (const PropertyInfo &pinfo : plist) {
5755 if (!(pinfo.usage & PROPERTY_USAGE_STORAGE)) {
5756 continue;
5757 }
5758
5759 if (pinfo.type != Variant::ARRAY && pinfo.type != Variant::DICTIONARY && pinfo.type != Variant::OBJECT) {
5760 continue;
5761 }
5762 if (find_recursive_resources(r->get(pinfo.name), r_resources_found)) {
5763 return true;
5764 }
5765 }
5766
5767 r_resources_found.erase(r.ptr());
5768 } break;
5769 default: {
5770 }
5771 }
5772 return false;
5773}
5774
5775bool EditorNode::_find_scene_in_use(Node *p_node, const String &p_path) const {
5776 if (p_node->get_scene_file_path() == p_path) {
5777 return true;
5778 }
5779
5780 for (int i = 0; i < p_node->get_child_count(); i++) {
5781 if (_find_scene_in_use(p_node->get_child(i), p_path)) {
5782 return true;
5783 }
5784 }
5785
5786 return false;
5787}
5788
5789bool EditorNode::close_scene() {
5790 int tab_index = editor_data.get_edited_scene();
5791 if (tab_index == 0 && get_edited_scene() == nullptr && editor_data.get_scene_path(tab_index).is_empty()) {
5792 return false;
5793 }
5794
5795 tab_closing_idx = tab_index;
5796 current_menu_option = SCENE_CLOSE;
5797 _discard_changes();
5798 changing_scene = false;
5799 return true;
5800}
5801
5802bool EditorNode::is_scene_in_use(const String &p_path) {
5803 Node *es = get_edited_scene();
5804 if (es) {
5805 return _find_scene_in_use(es, p_path);
5806 }
5807 return false;
5808}
5809
5810ProcessID EditorNode::has_child_process(ProcessID p_pid) const {
5811 return project_run_bar->has_child_process(p_pid);
5812}
5813
5814void EditorNode::stop_child_process(ProcessID p_pid) {
5815 project_run_bar->stop_child_process(p_pid);
5816}
5817
5818Ref<Script> EditorNode::get_object_custom_type_base(const Object *p_object) const {
5819 ERR_FAIL_NULL_V(p_object, nullptr);
5820
5821 const Node *node = Object::cast_to<const Node>(p_object);
5822 if (node && node->has_meta(SceneStringName(_custom_type_script))) {
5823 return PropertyUtils::get_custom_type_script(node);
5824 }
5825
5826 Ref<Script> scr = p_object->get_script();
5827
5828 if (scr.is_valid()) {
5829 // Uncommenting would break things! Consider adding a parameter if you need it.
5830 // StringName name = EditorNode::get_editor_data().script_class_get_name(base_script->get_path());
5831 // if (name != StringName()) {
5832 // return name;
5833 // }
5834
5835 // TODO: Should probably be deprecated in 4.x
5836 StringName base = scr->get_instance_base_type();
5837 if (base != StringName() && EditorNode::get_editor_data().get_custom_types().has(base)) {
5838 const Vector<EditorData::CustomType> &types = EditorNode::get_editor_data().get_custom_types()[base];
5839
5840 Ref<Script> base_scr = scr;
5841 while (base_scr.is_valid()) {
5842 for (int i = 0; i < types.size(); ++i) {
5843 if (types[i].script == base_scr) {
5844 return types[i].script;
5845 }
5846 }
5847 base_scr = base_scr->get_base_script();
5848 }
5849 }
5850 }
5851
5852 return nullptr;
5853}
5854
5855StringName EditorNode::get_object_custom_type_name(const Object *p_object) const {
5856 ERR_FAIL_NULL_V(p_object, StringName());
5857
5858 Ref<Script> scr = p_object->get_script();
5859 if (scr.is_null() && Object::cast_to<Script>(p_object)) {
5860 scr = p_object;
5861 }
5862
5863 if (scr.is_valid()) {
5864 Ref<Script> base_scr = scr;
5865 while (base_scr.is_valid()) {
5866 StringName name = EditorNode::get_editor_data().script_class_get_name(base_scr->get_path());
5867 if (name != StringName()) {
5868 return name;
5869 }
5870
5871 // TODO: Should probably be deprecated in 4.x.
5872 StringName base = base_scr->get_instance_base_type();
5873 if (base != StringName() && EditorNode::get_editor_data().get_custom_types().has(base)) {
5874 const Vector<EditorData::CustomType> &types = EditorNode::get_editor_data().get_custom_types()[base];
5875 for (int i = 0; i < types.size(); ++i) {
5876 if (types[i].script == base_scr) {
5877 return types[i].name;
5878 }
5879 }
5880 }
5881 base_scr = base_scr->get_base_script();
5882 }
5883 }
5884
5885 return StringName();
5886}
5887
5888void EditorNode::_pick_main_scene_custom_action(const String &p_custom_action_name) {
5889 if (p_custom_action_name == "select_current") {
5890 Node *scene = editor_data.get_edited_scene_root();
5891
5892 if (!scene) {
5893 show_warning(TTR("There is no defined scene to run."));
5894 return;
5895 }
5896
5897 pick_main_scene->hide();
5898
5899 if (!FileAccess::exists(scene->get_scene_file_path())) {
5900 current_menu_option = SAVE_AND_RUN_MAIN_SCENE;
5901 _menu_option_confirm(SCENE_SAVE_AS_SCENE, true);
5902 file->set_title(TTR("Save scene before running..."));
5903 } else {
5904 current_menu_option = SETTINGS_PICK_MAIN_SCENE;
5905 _dialog_action(scene->get_scene_file_path());
5906 }
5907 }
5908}
5909
5910Ref<Texture2D> EditorNode::_get_class_or_script_icon(const String &p_class, const String &p_script_path, const String &p_fallback, bool p_fallback_script_to_theme, bool p_skip_fallback_virtual) {
5911 ERR_FAIL_COND_V_MSG(p_class.is_empty(), nullptr, "Class name cannot be empty.");
5912 EditorData &ed = EditorNode::get_editor_data();
5913
5914 // Check for a script icon first.
5915 if (!p_script_path.is_empty()) {
5916 Ref<Texture2D> script_icon = ed.get_script_icon(p_script_path);
5917 if (script_icon.is_valid()) {
5918 return script_icon;
5919 }
5920
5921 if (p_fallback_script_to_theme) {
5922 // Look for the native base type in the editor theme. This is relevant for
5923 // scripts extending other scripts and for built-in classes.
5924 String base_type;
5925 if (ScriptServer::is_global_class(p_class)) {
5926 base_type = ScriptServer::get_global_class_native_base(p_class);
5927 } else {
5928 Ref<Script> scr = ResourceLoader::load(p_script_path, "Script");
5929 if (scr.is_valid()) {
5930 base_type = scr->get_instance_base_type();
5931 }
5932 }
5933 if (theme.is_valid()) {
5934 bool instantiable = false;
5935
5936 // If the class doesn't exist or isn't global, then it's not instantiable
5937 if (ClassDB::class_exists(p_class)) {
5938 instantiable = !ClassDB::is_virtual(p_class) && ClassDB::can_instantiate(p_class);
5939 } else if (ScriptServer::is_global_class(p_class)) {
5940 instantiable = !ScriptServer::is_global_class_abstract(p_class);
5941 }
5942
5943 return _get_class_or_script_icon(base_type, "", "", false, p_skip_fallback_virtual || instantiable);
5944 }
5945 }
5946 }
5947
5948 // Script was not valid or didn't yield any useful values, try the class name
5949 // directly.
5950
5951 // Check if the class name is an extension-defined type.
5952 Ref<Texture2D> ext_icon = ed.extension_class_get_icon(p_class);
5953 if (ext_icon.is_valid()) {
5954 return ext_icon;
5955 }
5956
5957 // Check if the class name is a custom type.
5958 // TODO: Should probably be deprecated in 4.x
5959 const EditorData::CustomType *ctype = ed.get_custom_type_by_name(p_class);
5960 if (ctype && ctype->icon.is_valid()) {
5961 return ctype->icon;
5962 }
5963
5964 // Look up the class name or the fallback name in the editor theme.
5965 // This is only relevant for built-in classes.
5966 if (theme.is_valid()) {
5967 if (theme->has_icon(p_class, EditorStringName(EditorIcons))) {
5968 return theme->get_icon(p_class, EditorStringName(EditorIcons));
5969 }
5970
5971 if (!p_fallback.is_empty() && theme->has_icon(p_fallback, EditorStringName(EditorIcons))) {
5972 return theme->get_icon(p_fallback, EditorStringName(EditorIcons));
5973 }
5974
5975 // If the fallback is empty or wasn't found, use the default fallback.
5976 if (ClassDB::class_exists(p_class)) {
5977 if (!p_skip_fallback_virtual) {
5978 bool instantiable = !ClassDB::is_virtual(p_class) && ClassDB::can_instantiate(p_class);
5979 if (!instantiable) {
5980 if (ClassDB::is_parent_class(p_class, SNAME("Node"))) {
5981 return theme->get_icon("NodeDisabled", EditorStringName(EditorIcons));
5982 } else {
5983 return theme->get_icon("ObjectDisabled", EditorStringName(EditorIcons));
5984 }
5985 }
5986 }
5987 StringName parent = ClassDB::get_parent_class_nocheck(p_class);
5988 if (parent) {
5989 // Skip virtual class if `p_skip_fallback_virtual` is true or `p_class` is instantiable.
5990 return _get_class_or_script_icon(parent, "", "", false, true);
5991 }
5992 }
5993 }
5994
5995 return nullptr;
5996}
5997
5998Ref<Texture2D> EditorNode::get_object_icon(const Object *p_object, const String &p_fallback) {
5999 ERR_FAIL_NULL_V_MSG(p_object, nullptr, "Object cannot be null.");
6000
6001 Ref<Script> scr = p_object->get_script();
6002
6003 const EditorDebuggerRemoteObjects *robjs = Object::cast_to<EditorDebuggerRemoteObjects>(p_object);
6004 if (robjs) {
6005 String class_name;
6006 if (scr.is_valid()) {
6007 class_name = scr->get_global_name();
6008
6009 if (class_name.is_empty()) {
6010 // If there is no class_name in this script we just take the script path.
6011 class_name = scr->get_path();
6012 }
6013 }
6014
6015 if (class_name.is_empty()) {
6016 return get_class_icon(robjs->type_name, p_fallback);
6017 }
6018
6019 return get_class_icon(class_name, p_fallback);
6020 }
6021
6022 if (scr.is_null() && p_object->is_class("Script")) {
6023 scr = p_object;
6024 }
6025
6026 if (Object::cast_to<MultiNodeEdit>(p_object)) {
6027 return get_class_icon(Object::cast_to<MultiNodeEdit>(p_object)->get_edited_class_name(), p_fallback);
6028 } else {
6029 return _get_class_or_script_icon(p_object->get_class(), scr.is_valid() ? scr->get_path() : String(), p_fallback);
6030 }
6031}
6032
6033Ref<Texture2D> EditorNode::get_class_icon(const String &p_class, const String &p_fallback) {
6034 ERR_FAIL_COND_V_MSG(p_class.is_empty(), nullptr, "Class name cannot be empty.");
6035 const Pair<String, String> key(p_class, p_fallback);
6036
6037 // Take from the local cache, if available.
6038 {
6039 Ref<Texture2D> *icon = class_icon_cache.getptr(key);
6040 if (icon) {
6041 return *icon;
6042 }
6043 }
6044
6045 String script_path;
6046 if (ScriptServer::is_global_class(p_class)) {
6047 script_path = ScriptServer::get_global_class_path(p_class);
6048 } else if (!p_class.get_extension().is_empty() && ResourceLoader::exists(p_class)) { // If the script is not a class_name we check if the script resource exists.
6049 script_path = p_class;
6050 }
6051
6052 Ref<Texture2D> icon = _get_class_or_script_icon(p_class, script_path, p_fallback, true);
6053 class_icon_cache[key] = icon;
6054 return icon;
6055}
6056
6057bool EditorNode::is_object_of_custom_type(const Object *p_object, const StringName &p_class) {
6058 ERR_FAIL_NULL_V(p_object, false);
6059
6060 Ref<Script> scr = p_object->get_script();
6061 if (scr.is_null() && Object::cast_to<Script>(p_object)) {
6062 scr = p_object;
6063 }
6064
6065 if (scr.is_valid()) {
6066 Ref<Script> base_script = scr;
6067 while (base_script.is_valid()) {
6068 StringName name = EditorNode::get_editor_data().script_class_get_name(base_script->get_path());
6069 if (name == p_class) {
6070 return true;
6071 }
6072 base_script = base_script->get_base_script();
6073 }
6074 }
6075 return false;
6076}
6077
6078// Used to track the progress of tasks in the CLI output (since we don't have any other frame of reference).
6079static HashMap<String, int> progress_total_steps;
6080
6081static String last_progress_task;
6082static String last_progress_state;
6083static int last_progress_step = 0;
6084static double last_progress_time = 0;
6085
6086void EditorNode::progress_add_task(const String &p_task, const String &p_label, int p_steps, bool p_can_cancel) {
6087 if (!singleton) {
6088 return;
6089 } else if (singleton->cmdline_mode) {
6090 print_line_rich(vformat("[ 0%% ] [color=gray][b]%s[/b] | Started %s (%d steps)[/color]", p_task, p_label, p_steps));
6091 progress_total_steps[p_task] = p_steps;
6092 } else if (singleton->progress_dialog) {
6093 singleton->progress_dialog->add_task(p_task, p_label, p_steps, p_can_cancel);
6094 }
6095}
6096
6097bool EditorNode::progress_task_step(const String &p_task, const String &p_state, int p_step, bool p_force_refresh) {
6098 if (!singleton) {
6099 return false;
6100 } else if (singleton->cmdline_mode) {
6101 double current_time = USEC_TO_SEC(OS::get_singleton()->get_ticks_usec());
6102 double elapsed_time = current_time - last_progress_time;
6103 if (p_task != last_progress_task || p_state != last_progress_state || p_step != last_progress_step || elapsed_time >= 1.0) {
6104 // Only print the progress if it's changed since the last print, or if one second has passed.
6105 // This prevents multithreaded import from printing the same progress too often, which would bloat the log file.
6106 const int percent = (p_step / float(progress_total_steps[p_task] + 1)) * 100;
6107 print_line_rich(vformat("[%4d%% ] [color=gray][b]%s[/b] | %s[/color]", percent, p_task, p_state));
6108 last_progress_task = p_task;
6109 last_progress_state = p_state;
6110 last_progress_step = p_step;
6111 last_progress_time = current_time;
6112 }
6113 return false;
6114 } else if (singleton->progress_dialog) {
6115 return singleton->progress_dialog->task_step(p_task, p_state, p_step, p_force_refresh);
6116 } else {
6117 return false;
6118 }
6119}
6120
6121void EditorNode::progress_end_task(const String &p_task) {
6122 if (!singleton) {
6123 return;
6124 } else if (singleton->cmdline_mode) {
6125 progress_total_steps.erase(p_task);
6126 print_line_rich(vformat("[color=green][ DONE ][/color] [b]%s[/b]\n", p_task));
6127 } else if (singleton->progress_dialog) {
6128 singleton->progress_dialog->end_task(p_task);
6129 }
6130}
6131
6132void EditorNode::progress_add_task_bg(const String &p_task, const String &p_label, int p_steps) {
6133 singleton->progress_hb->add_task(p_task, p_label, p_steps);
6134}
6135
6136void EditorNode::progress_task_step_bg(const String &p_task, int p_step) {
6137 singleton->progress_hb->task_step(p_task, p_step);
6138}
6139
6140void EditorNode::progress_end_task_bg(const String &p_task) {
6141 singleton->progress_hb->end_task(p_task);
6142}
6143
6144void EditorNode::_progress_dialog_visibility_changed() {
6145 // Open the io errors after the progress dialog is closed.
6146 if (load_errors_queued_to_display && !progress_dialog->is_visible()) {
6147 EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
6148 load_errors_queued_to_display = false;
6149 }
6150}
6151
6152void EditorNode::_load_error_dialog_visibility_changed() {
6153 if (!load_error_dialog->is_visible()) {
6154 load_errors->clear();
6155 }
6156}
6157
6158String EditorNode::_get_system_info() const {
6159 String distribution_name = OS::get_singleton()->get_distribution_name();
6160 if (distribution_name.is_empty()) {
6161 distribution_name = OS::get_singleton()->get_name();
6162 }
6163 if (distribution_name.is_empty()) {
6164 distribution_name = "Other";
6165 }
6166 const String distribution_version = OS::get_singleton()->get_version_alias();
6167
6168 String godot_version = "Godot v" + String(GODOT_VERSION_FULL_CONFIG);
6169 if (String(GODOT_VERSION_BUILD) != "official") {
6170 String hash = String(GODOT_VERSION_HASH);
6171 hash = hash.is_empty() ? String("unknown") : vformat("(%s)", hash.left(9));
6172 godot_version += " " + hash;
6173 }
6174
6175 String display_session_type;
6176#ifdef LINUXBSD_ENABLED
6177 // `remove_char` is necessary, because `capitalize` introduces a whitespace between "x" and "11".
6178 display_session_type = OS::get_singleton()->get_environment("XDG_SESSION_TYPE").capitalize().remove_char(' ');
6179#endif // LINUXBSD_ENABLED
6180 String driver_name = OS::get_singleton()->get_current_rendering_driver_name().to_lower();
6181 String rendering_method = OS::get_singleton()->get_current_rendering_method().to_lower();
6182
6183 const String rendering_device_name = RenderingServer::get_singleton()->get_video_adapter_name();
6184
6185 String device_type_string;
6186#ifdef RD_ENABLED
6187 RenderingDeviceEnums::DeviceType device_type = RenderingServer::get_singleton()->get_video_adapter_type();
6188 switch (device_type) {
6189 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_INTEGRATED_GPU:
6190 device_type_string = "integrated";
6191 break;
6192 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_DISCRETE_GPU:
6193 device_type_string = "dedicated";
6194 break;
6195 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_VIRTUAL_GPU:
6196 device_type_string = "virtual";
6197 break;
6198 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_CPU:
6199 device_type_string = "(software emulation on CPU)";
6200 break;
6201 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_OTHER:
6202 case RenderingDeviceEnums::DeviceType::DEVICE_TYPE_MAX:
6203 break; // Can't happen, but silences warning for DEVICE_TYPE_MAX
6204 }
6205#endif // RD_ENABLED
6206
6207 const Vector<String> video_adapter_driver_info = OS::get_singleton()->get_video_adapter_driver_info();
6208
6209 const String processor_name = OS::get_singleton()->get_processor_name();
6210 const int processor_count = OS::get_singleton()->get_processor_count();
6211
6212 const String audio_driver_name = AudioServer::get_singleton()->get_driver_name();
6213 const float mix_rate = AudioServer::get_singleton()->get_mix_rate();
6214
6215 AuSE::SpeakerMode speaker_mode = AudioServer::get_singleton()->get_speaker_mode();
6216 String speaker_mode_string;
6217 switch (speaker_mode) {
6218 case AuSE::SpeakerMode::SPEAKER_MODE_STEREO:
6219 speaker_mode_string = "Stereo/mono";
6220 break;
6221 case AuSE::SpeakerMode::SPEAKER_SURROUND_31:
6222 speaker_mode_string = "Surround 3.1";
6223 break;
6224 case AuSE::SpeakerMode::SPEAKER_SURROUND_51:
6225 speaker_mode_string = "Surround 5.1";
6226 break;
6227 case AuSE::SpeakerMode::SPEAKER_SURROUND_71:
6228 speaker_mode_string = "Surround 7.1";
6229 break;
6230 }
6231
6232 // Prettify
6233 if (rendering_method == "forward_plus") {
6234 rendering_method = "Forward+";
6235 } else if (rendering_method == "mobile") {
6236 rendering_method = "Mobile";
6237 } else if (rendering_method == "gl_compatibility") {
6238 rendering_method = "Compatibility";
6239 }
6240 if (driver_name == "vulkan") {
6241 driver_name = "Vulkan";
6242 } else if (driver_name == "d3d12") {
6243 driver_name = "Direct3D 12";
6244 } else if (driver_name == "opengl3_angle") {
6245 driver_name = "OpenGL ES 3/ANGLE";
6246 } else if (driver_name == "opengl3_es") {
6247 driver_name = "OpenGL ES 3";
6248 } else if (driver_name == "opengl3") {
6249 if (OS::get_singleton()->get_gles_over_gl()) {
6250 driver_name = "OpenGL 3";
6251 } else {
6252 driver_name = "OpenGL ES 3";
6253 }
6254 } else if (driver_name == "metal") {
6255 driver_name = "Metal";
6256 }
6257
6258 // Join info.
6259 Vector<String> info;
6260 info.push_back(godot_version);
6261 String distribution_display_session_type = distribution_name;
6262 if (!distribution_version.is_empty()) {
6263 distribution_display_session_type += " " + distribution_version;
6264 }
6265 if (!display_session_type.is_empty()) {
6266 distribution_display_session_type += " on " + display_session_type;
6267 }
6268 info.push_back(distribution_display_session_type);
6269
6270 String display_driver_window_mode;
6271#ifdef LINUXBSD_ENABLED
6272 // `remove_char` is necessary, because `capitalize` introduces a whitespace between "x" and "11".
6273 display_driver_window_mode = DisplayServer::get_singleton()->get_name().capitalize().remove_char(' ') + " display driver";
6274#endif // LINUXBSD_ENABLED
6275 if (!display_driver_window_mode.is_empty()) {
6276 display_driver_window_mode += ", ";
6277 }
6278 display_driver_window_mode += get_viewport()->is_embedding_subwindows() ? "Single-window" : "Multi-window";
6279
6280 if (DisplayServer::get_singleton()->get_screen_count() == 1) {
6281 display_driver_window_mode += ", " + itos(DisplayServer::get_singleton()->get_screen_count()) + " monitor";
6282 } else {
6283 display_driver_window_mode += ", " + itos(DisplayServer::get_singleton()->get_screen_count()) + " monitors";
6284 }
6285
6286 // List resolution and refresh rate for each monitor.
6287 display_driver_window_mode += " (";
6288 for (int i = 0; i < DisplayServer::get_singleton()->get_screen_count(); i++) {
6289 const Size2i screen_size = DisplayServer::get_singleton()->screen_get_size(i);
6290 display_driver_window_mode += vformat("%dx%d @ %.2f Hz", screen_size.x, screen_size.y, DisplayServer::get_singleton()->screen_get_refresh_rate(i));
6291 if (i < DisplayServer::get_singleton()->get_screen_count() - 1) {
6292 display_driver_window_mode += ", ";
6293 }
6294 }
6295 display_driver_window_mode += ")";
6296
6297 info.push_back(display_driver_window_mode);
6298
6299 info.push_back(vformat("%s (%s)", driver_name, rendering_method));
6300
6301 String graphics;
6302 if (!device_type_string.is_empty()) {
6303 graphics = device_type_string + " ";
6304 }
6305 graphics += rendering_device_name;
6306 if (video_adapter_driver_info.size() == 2) { // This vector is always either of length 0 or 2.
6307 const String &vad_name = video_adapter_driver_info[0];
6308 const String &vad_version = video_adapter_driver_info[1]; // Version could be potentially empty on Linux/BSD.
6309 if (!vad_version.is_empty()) {
6310 graphics += vformat(" (%s; %s)", vad_name, vad_version);
6311 } else if (!vad_name.is_empty()) {
6312 graphics += vformat(" (%s)", vad_name);
6313 }
6314 }
6315 info.push_back(graphics);
6316
6317 info.push_back(vformat("%s (%d threads)", processor_name, processor_count));
6318
6319 const int64_t system_ram = OS::get_singleton()->get_memory_info()["physical"];
6320 if (system_ram > 0) {
6321 // If the memory info is available, display it.
6322 info.push_back(vformat("%s memory", String::humanize_size(system_ram)));
6323 }
6324
6325 info.push_back(vformat("%s (%d Hz, %s)", audio_driver_name, int(mix_rate), speaker_mode_string));
6326
6327 return String(" - ").join(info);
6328}
6329
6330Ref<Texture2D> EditorNode::_file_dialog_get_icon(const String &p_path) {
6331 EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem_path(p_path.get_base_dir());
6332 if (efsd) {
6333 String file = p_path.get_file();
6334 for (int i = 0; i < efsd->get_file_count(); i++) {
6335 if (efsd->get_file(i) == file) {
6336 String type = efsd->get_file_type(i);
6337
6338 if (singleton->icon_type_cache.has(type)) {
6339 return singleton->icon_type_cache[type];
6340 } else {
6341 return singleton->icon_type_cache["Object"];
6342 }
6343 }
6344 }
6345 }
6346
6347 return singleton->icon_type_cache["Object"];
6348}
6349
6350Ref<Texture2D> EditorNode::_file_dialog_get_thumbnail(const String &p_path) {
6351 Ref<ImageTexture> texture = singleton->default_thumbnail->duplicate();
6352 EditorResourcePreview::get_singleton()->queue_resource_preview(p_path, callable_mp_static(EditorNode::_file_dialog_thumbnail_callback).bind(texture));
6353 return texture;
6354}
6355
6356void EditorNode::_file_dialog_thumbnail_callback(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Ref<ImageTexture> p_texture) {
6357 ERR_FAIL_COND(p_texture.is_null());
6358 if (p_preview.is_valid()) {
6359 p_texture->set_image(p_preview->get_image());
6360 }
6361}
6362
6363void EditorNode::_build_icon_type_cache() {
6364 List<StringName> tl;
6365 theme->get_icon_list(EditorStringName(EditorIcons), &tl);
6366 for (const StringName &E : tl) {
6367 if (!ClassDB::class_exists(E)) {
6368 continue;
6369 }
6370 icon_type_cache[E] = theme->get_icon(E, EditorStringName(EditorIcons));
6371 }
6372}
6373
6374void EditorNode::_enable_pending_addons() {
6375 for (uint32_t i = 0; i < pending_addons.size(); i++) {
6376 set_addon_plugin_enabled(pending_addons[i], true);
6377 }
6378 pending_addons.clear();
6379}
6380
6381void EditorNode::_file_dialog_register(FileDialog *p_dialog) {
6382 singleton->file_dialogs.insert(p_dialog);
6383}
6384
6385void EditorNode::_file_dialog_unregister(FileDialog *p_dialog) {
6386 singleton->file_dialogs.erase(p_dialog);
6387}
6388
6389Vector<EditorNodeInitCallback> EditorNode::_init_callbacks;
6390
6391void EditorNode::_begin_first_scan() {
6392 if (!waiting_for_first_scan) {
6393 return;
6394 }
6395 requested_first_scan = true;
6396}
6397
6398Error EditorNode::export_preset(const String &p_preset, const String &p_path, bool p_debug, bool p_pack_only, bool p_android_build_template, bool p_patch, const Vector<String> &p_patches) {
6399 export_defer.preset = p_preset;
6400 export_defer.path = p_path;
6401 export_defer.debug = p_debug;
6402 export_defer.pack_only = p_pack_only;
6403 export_defer.android_build_template = p_android_build_template;
6404 export_defer.patch = p_patch;
6405 export_defer.patches = p_patches;
6406 cmdline_mode = true;
6407 return OK;
6408}
6409
6410bool EditorNode::is_project_exporting() const {
6411 return project_export && project_export->is_exporting();
6412}
6413
6414void EditorNode::show_save_accept(const String &p_text, const String &p_ok_text) {
6415 current_menu_option = -1;
6416 if (save_accept) {
6417 _close_save_scene_progress();
6418 save_accept->set_ok_button_text(p_ok_text);
6419 save_accept->set_text(p_text);
6420 save_accept->reset_size();
6421 EditorInterface::get_singleton()->popup_dialog_centered_clamped(save_accept, Size2i(), 0.0);
6422 }
6423}
6424
6425void EditorNode::show_warning(const String &p_text, const String &p_title) {
6426 if (warning) {
6427 _close_save_scene_progress();
6428 warning->set_text(p_text);
6429 warning->set_title(p_title);
6430 warning->reset_size();
6431 EditorInterface::get_singleton()->popup_dialog_centered_clamped(warning, Size2i(), 0.0);
6432 } else {
6433 WARN_PRINT(p_title + " " + p_text);
6434 }
6435}
6436
6437void EditorNode::_copy_warning(const String &p_str) {
6438 DisplayServer::get_singleton()->clipboard_set(warning->get_text());
6439}
6440
6441void EditorNode::_save_editor_layout() {
6442 if (!load_editor_layout_done) {
6443 return;
6444 }
6445 Ref<ConfigFile> config;
6446 config.instantiate();
6447 // Load and amend existing config if it exists.
6448 config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
6449
6450 editor_dock_manager->save_docks_to_config(config, "docks");
6451 _save_open_scenes_to_config(config);
6452 _save_central_editor_layout_to_config(config);
6453 _save_window_settings_to_config(config, "EditorWindow");
6454 editor_data.get_plugin_window_layout(config);
6455
6456 config->save(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
6457}
6458
6459void EditorNode::_save_open_scenes_to_config(Ref<ConfigFile> p_layout) {
6460 PackedStringArray scenes;
6461 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
6462 String path = editor_data.get_scene_path(i);
6463 if (path.is_empty()) {
6464 continue;
6465 }
6466 scenes.push_back(path);
6467 }
6468 p_layout->set_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes", scenes);
6469
6470 String currently_edited_scene_path = editor_data.get_scene_path(editor_data.get_edited_scene());
6471 p_layout->set_value(EDITOR_NODE_CONFIG_SECTION, "current_scene", currently_edited_scene_path);
6472}
6473
6474void EditorNode::save_editor_layout_delayed() {
6475 editor_layout_save_delay_timer->start();
6476}
6477
6478void EditorNode::_load_editor_layout() {
6479 EditorProgress ep("loading_editor_layout", TTR("Loading editor"), 5);
6480 ep.step(TTR("Loading editor layout..."), 0, true);
6481 Ref<ConfigFile> config;
6482 config.instantiate();
6483 Error err = config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
6484 if (err != OK) { // No config.
6485 // If config is not found, expand the res:// folder and favorites by default.
6486 TreeItem *root = FileSystemDock::get_singleton()->get_tree_control()->get_item_with_metadata("res://", 0);
6487 if (root) {
6488 root->set_collapsed(false);
6489 }
6490
6491 TreeItem *favorites = FileSystemDock::get_singleton()->get_tree_control()->get_item_with_metadata("Favorites", 0);
6492 if (favorites) {
6493 favorites->set_collapsed(false);
6494 }
6495
6496 if (overridden_default_layout) {
6497 _layout_menu_option(LAYOUT_DEFAULT);
6498 } else {
6499 ep.step(TTR("Loading docks..."), 1, true);
6500 // Initialize some default values.
6501 bottom_panel->load_layout_from_config(default_layout, EDITOR_NODE_CONFIG_SECTION);
6502 }
6503 } else {
6504 ep.step(TTR("Loading docks..."), 1, true);
6505 editor_dock_manager->load_docks_from_config(config, "docks", true);
6506
6507 ep.step(TTR("Reopening scenes..."), 2, true);
6508 _load_open_scenes_from_config(config);
6509
6510 ep.step(TTR("Loading central editor layout..."), 3, true);
6511 _load_central_editor_layout_from_config(config);
6512
6513 ep.step(TTR("Loading plugin window layout..."), 4, true);
6514 editor_data.set_plugin_window_layout(config);
6515
6516 ep.step(TTR("Editor layout ready."), 5, true);
6517 }
6518 load_editor_layout_done = true;
6519}
6520
6521void EditorNode::_save_central_editor_layout_to_config(Ref<ConfigFile> p_config_file) {
6522 // Bottom panel.
6523
6524 bottom_panel->save_layout_to_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
6525
6526 // Debugger tab.
6527
6528 int selected_default_debugger_tab_idx = EditorDebuggerNode::get_singleton()->get_default_debugger()->get_current_debugger_tab();
6529 p_config_file->set_value(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx", selected_default_debugger_tab_idx);
6530}
6531
6532void EditorNode::_load_central_editor_layout_from_config(Ref<ConfigFile> p_config_file) {
6533 // Bottom panel.
6534
6535 bottom_panel->load_layout_from_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
6536
6537 // Debugger tab.
6538
6539 if (p_config_file->has_section_key(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx")) {
6540 int selected_default_debugger_tab_idx = p_config_file->get_value(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx");
6541 EditorDebuggerNode::get_singleton()->get_default_debugger()->switch_to_debugger(selected_default_debugger_tab_idx);
6542 }
6543}
6544
6545void EditorNode::_save_window_settings_to_config(Ref<ConfigFile> p_layout, const String &p_section) {
6546 Window *w = get_window();
6547 if (w) {
6548 p_layout->set_value(p_section, "screen", w->get_current_screen());
6549
6550 Size2i win_size = w->get_size();
6551
6552 if (DisplayServer::get_singleton()->has_feature(DisplayServerEnums::FEATURE_SELF_FITTING_WINDOWS)) {
6553 // Work around logical size issues with HiDPI on Wayland. See GH-110643.
6554 float win_scale = DisplayServer::get_singleton()->window_get_scale(w->get_window_id());
6555
6556 win_size.width /= win_scale;
6557 win_size.height /= win_scale;
6558 }
6559
6560 Window::Mode mode = w->get_mode();
6561 switch (mode) {
6562 case Window::MODE_WINDOWED:
6563 p_layout->set_value(p_section, "mode", "windowed");
6564 p_layout->set_value(p_section, "size", win_size);
6565 break;
6566 case Window::MODE_FULLSCREEN:
6567 case Window::MODE_EXCLUSIVE_FULLSCREEN:
6568 p_layout->set_value(p_section, "mode", "fullscreen");
6569 break;
6570 case Window::MODE_MINIMIZED:
6571 if (was_window_windowed_last) {
6572 p_layout->set_value(p_section, "mode", "windowed");
6573 p_layout->set_value(p_section, "size", w->get_size());
6574 } else {
6575 p_layout->set_value(p_section, "mode", "maximized");
6576 }
6577 break;
6578 default:
6579 p_layout->set_value(p_section, "mode", "maximized");
6580 break;
6581 }
6582
6583 p_layout->set_value(p_section, "position", w->get_position());
6584 }
6585}
6586
6587void EditorNode::_load_open_scenes_from_config(Ref<ConfigFile> p_layout) {
6588 if (Engine::get_singleton()->is_recovery_mode_hint()) {
6589 return;
6590 }
6591
6592 if (!bool(EDITOR_GET("interface/scene_tabs/restore_scenes_on_load"))) {
6593 return;
6594 }
6595
6596 if (!p_layout->has_section_key(EDITOR_NODE_CONFIG_SECTION, "open_scenes")) {
6597 return;
6598 }
6599
6600 restoring_scenes = true;
6601
6602 const PackedStringArray scenes = p_layout->get_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes");
6603 for (const String &scene_path : scenes) {
6604 if (FileAccess::exists(scene_path)) {
6605 load_scene(scene_path);
6606 }
6607 }
6608
6609 bool current_scene_found = false;
6610 const String current_scene = p_layout->get_value(EDITOR_NODE_CONFIG_SECTION, "current_scene", String());
6611 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
6612 if (editor_data.get_scene_path(i) == current_scene) {
6613 _set_current_scene_nocheck(i, true);
6614 current_scene_found = true;
6615 break;
6616 }
6617 }
6618 if (!current_scene_found && editor_data.get_edited_scene_count() > 0) {
6619 _set_current_scene_nocheck(0);
6620 }
6621
6622 save_editor_layout_delayed();
6623
6624 restoring_scenes = false;
6625}
6626
6627bool EditorNode::has_scenes_in_session() {
6628 if (!bool(EDITOR_GET("interface/scene_tabs/restore_scenes_on_load"))) {
6629 return false;
6630 }
6631 Ref<ConfigFile> config;
6632 config.instantiate();
6633 Error err = config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
6634 if (err != OK) {
6635 return false;
6636 }
6637 if (!config->has_section(EDITOR_NODE_CONFIG_SECTION) || !config->has_section_key(EDITOR_NODE_CONFIG_SECTION, "open_scenes")) {
6638 return false;
6639 }
6640 Array scenes = config->get_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes");
6641 return !scenes.is_empty();
6642}
6643
6644void EditorNode::undo() {
6645 _menu_option_confirm(SCENE_UNDO, true);
6646}
6647
6648void EditorNode::redo() {
6649 _menu_option_confirm(SCENE_REDO, true);
6650}
6651
6652bool EditorNode::ensure_main_scene(bool p_from_native) {
6653 pick_main_scene->set_meta("from_native", p_from_native); // Whether from play button or native run.
6654 String main_scene = GLOBAL_GET("application/run/main_scene");
6655
6656 if (main_scene.is_empty()) {
6657 current_menu_option = -1;
6658 pick_main_scene->set_text(TTR("No main scene has ever been defined. Select one?\nYou can change it later in \"Project Settings\" under the 'application' category."));
6659 pick_main_scene->popup_centered();
6660
6661 if (editor_data.get_edited_scene_root()) {
6662 select_current_scene_button->set_disabled(false);
6663 select_current_scene_button->grab_focus();
6664 } else {
6665 select_current_scene_button->set_disabled(true);
6666 }
6667
6668 return false;
6669 }
6670
6671 if (!FileAccess::exists(main_scene)) {
6672 current_menu_option = -1;
6673 pick_main_scene->set_text(vformat(TTR("Selected scene '%s' does not exist. Select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
6674 pick_main_scene->popup_centered();
6675 return false;
6676 }
6677
6678 if (ResourceLoader::get_resource_type(main_scene) != "PackedScene") {
6679 current_menu_option = -1;
6680 pick_main_scene->set_text(vformat(TTR("Selected scene '%s' is not a scene file. Select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
6681 pick_main_scene->popup_centered();
6682 return false;
6683 }
6684
6685 return true;
6686}
6687
6688bool EditorNode::validate_custom_directory() {
6689 bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
6690
6691 if (use_custom_dir) {
6692 String data_dir = OS::get_singleton()->get_user_data_dir();
6693 Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_USERDATA);
6694 if (dir->change_dir(data_dir) != OK) {
6695 dir->make_dir_recursive(data_dir);
6696 if (dir->change_dir(data_dir) != OK) {
6697 open_project_settings->set_text(vformat(TTR("User data dir '%s' is not valid. Change to a valid one?"), data_dir));
6698 open_project_settings->popup_centered();
6699 return false;
6700 }
6701 }
6702 }
6703
6704 return true;
6705}
6706
6707void EditorNode::run_editor_script(const Ref<Script> &p_script) {
6708 Error err = p_script->reload(true); // Always hard reload the script before running.
6709 if (err != OK || !p_script->is_script_valid()) {
6710 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the script because it contains errors, check the output log."), EditorToaster::SEVERITY_WARNING);
6711 return;
6712 }
6713
6714 // Perform additional checks on the script to evaluate if it's runnable.
6715
6716 bool is_runnable = true;
6717 if (!ClassDB::is_parent_class(p_script->get_instance_base_type(), "EditorScript")) {
6718 is_runnable = false;
6719
6720 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the script because it doesn't extend EditorScript."), EditorToaster::SEVERITY_WARNING);
6721 }
6722 if (!p_script->is_tool()) {
6723 is_runnable = false;
6724
6725 if (p_script->get_class() == "GDScript") {
6726 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the script because it's not a tool script (add the @tool annotation at the top)."), EditorToaster::SEVERITY_WARNING);
6727 } else if (p_script->get_class() == "CSharpScript") {
6728 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the script because it's not a tool script (add the [Tool] attribute above the class definition)."), EditorToaster::SEVERITY_WARNING);
6729 } else {
6730 EditorToaster::get_singleton()->popup_str(TTR("Cannot run the script because it's not a tool script."), EditorToaster::SEVERITY_WARNING);
6731 }
6732 }
6733 if (!is_runnable) {
6734 return;
6735 }
6736
6737 Ref<EditorScript> es = memnew(EditorScript);
6738 es->set_script(p_script);
6739 es->run();
6740}
6741
6742void EditorNode::_immediate_dialog_confirmed() {
6743 immediate_dialog_confirmed = true;
6744}
6745bool EditorNode::immediate_confirmation_dialog(const String &p_text, const String &p_ok_text, const String &p_cancel_text, uint32_t p_wrap_width) {
6746 ConfirmationDialog *cd = memnew(ConfirmationDialog);
6747 cd->set_flag(Window::FLAG_RESIZE_DISABLED, true);
6748 cd->set_text(p_text);
6749 cd->set_ok_button_text(p_ok_text);
6750 cd->set_cancel_button_text(p_cancel_text);
6751 if (p_wrap_width > 0) {
6752 cd->set_autowrap(true);
6753 cd->get_label()->set_custom_minimum_size(Size2(p_wrap_width, 0) * EDSCALE);
6754 }
6755
6756 cd->connect(SceneStringName(confirmed), callable_mp(singleton, &EditorNode::_immediate_dialog_confirmed));
6757 singleton->gui_base->add_child(cd);
6758
6759 cd->popup_centered();
6760
6761 while (true) {
6762 DisplayServer::get_singleton()->process_events();
6763 Main::iteration();
6764 if (singleton->immediate_dialog_confirmed || !cd->is_visible()) {
6765 break;
6766 }
6767 }
6768
6769 memdelete(cd);
6770 return singleton->immediate_dialog_confirmed;
6771}
6772
6773bool EditorNode::is_cmdline_mode() {
6774 ERR_FAIL_NULL_V(singleton, false);
6775 return singleton->cmdline_mode;
6776}
6777
6778void EditorNode::cleanup() {
6779 _init_callbacks.clear();
6780}
6781
6782void EditorNode::_update_layouts_menu() {
6783 editor_layouts->clear();
6784 overridden_default_layout = false;
6785
6786 editor_layouts->reset_size();
6787 editor_layouts->add_shortcut(ED_SHORTCUT("layout/save", TTRC("Save Layout...")), LAYOUT_SAVE);
6788 editor_layouts->add_shortcut(ED_SHORTCUT("layout/delete", TTRC("Delete Layout...")), LAYOUT_DELETE);
6789 editor_layouts->add_separator();
6790
6791 Ref<ConfigFile> config;
6792 config.instantiate();
6793 Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
6794 if (err == OK && config->has_section("Default")) {
6795 overridden_default_layout = true;
6796 }
6797
6798 editor_layouts->add_shortcut(ED_SHORTCUT("layout/default", overridden_default_layout ? TTRC("Default (Overridden)") : TTRC("Default")), LAYOUT_DEFAULT);
6799
6800 if (err != OK) {
6801 return; // No config.
6802 }
6803
6804 Vector<String> layouts = config->get_sections();
6805 for (const String &layout : layouts) {
6806 if (layout != "Default" && !layout.contains_char('/')) {
6807 editor_layouts->add_item(layout);
6808 editor_layouts->set_item_auto_translate_mode(-1, AUTO_TRANSLATE_MODE_DISABLED);
6809 }
6810 }
6811}
6812
6813void EditorNode::_layout_menu_option(int p_id) {
6814 switch (p_id) {
6815 case LAYOUT_SAVE: {
6816 current_menu_option = p_id;
6817 layout_dialog->set_save_mode_enabled(true);
6818 layout_dialog->popup_centered();
6819 } break;
6820
6821 case LAYOUT_DELETE: {
6822 current_menu_option = p_id;
6823 layout_dialog->set_save_mode_enabled(false);
6824 layout_dialog->popup_centered();
6825 } break;
6826
6827 case LAYOUT_DEFAULT: {
6828 // Check if the default layout was overridden, and if so, select that instead.
6829 Ref<ConfigFile> config;
6830 config.instantiate();
6831 Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
6832 if (err == OK && config->has_section("Default")) {
6833 editor_dock_manager->load_docks_from_config(config, "Default");
6834 _save_editor_layout();
6835
6836 return;
6837 }
6838
6839 editor_dock_manager->load_docks_from_config(default_layout, "docks");
6840 _save_editor_layout();
6841 } break;
6842
6843 default: {
6844 Ref<ConfigFile> config;
6845 config.instantiate();
6846 Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
6847 if (err == OK) {
6848 editor_dock_manager->load_docks_from_config(config, editor_layouts->get_item_text(p_id));
6849 _save_editor_layout();
6850 }
6851 }
6852 }
6853}
6854
6855void EditorNode::_proceed_closing_scene_tabs() {
6856 List<String>::Element *E = tabs_to_close.front();
6857 if (!E) {
6858 if (_is_closing_editor()) {
6859 current_menu_option = tab_closing_menu_option;
6860 _menu_option_confirm(tab_closing_menu_option, true);
6861 } else {
6862 current_menu_option = -1;
6863 save_confirmation->hide();
6864 }
6865 return;
6866 }
6867 String scene_to_close = E->get();
6868 tabs_to_close.pop_front();
6869
6870 int tab_idx = -1;
6871 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
6872 if (editor_data.get_scene_path(i) == scene_to_close) {
6873 tab_idx = i;
6874 break;
6875 }
6876 }
6877 ERR_FAIL_COND(tab_idx < 0);
6878
6879 _scene_tab_closed(tab_idx);
6880}
6881
6882void EditorNode::_proceed_save_asing_scene_tabs() {
6883 if (scenes_to_save_as.is_empty()) {
6884 return;
6885 }
6886 int scene_idx = scenes_to_save_as.front()->get();
6887 scenes_to_save_as.pop_front();
6888 _set_current_scene(scene_idx);
6889 _menu_option_confirm(SCENE_MULTI_SAVE_AS_SCENE, false);
6890}
6891
6892bool EditorNode::_is_closing_editor() const {
6893 return tab_closing_menu_option == SCENE_QUIT || tab_closing_menu_option == PROJECT_QUIT_TO_PROJECT_MANAGER || tab_closing_menu_option == PROJECT_RELOAD_CURRENT_PROJECT;
6894}
6895
6896void EditorNode::_restart_editor(bool p_goto_project_manager) {
6897 exiting = true;
6898
6899 if (project_run_bar->is_playing()) {
6900 project_run_bar->stop_playing();
6901 }
6902
6903 String to_reopen;
6904 if (!p_goto_project_manager && get_tree()->get_edited_scene_root()) {
6905 to_reopen = get_tree()->get_edited_scene_root()->get_scene_file_path();
6906 }
6907
6908 _exit_editor(EXIT_SUCCESS);
6909
6910 List<String> args;
6911 for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_TOOL)) {
6912 args.push_back(a);
6913 }
6914
6915 if (p_goto_project_manager) {
6916 args.push_back("--project-manager");
6917
6918 // Setup working directory.
6919 const String exec_dir = OS::get_singleton()->get_executable_path().get_base_dir();
6920 if (!exec_dir.is_empty()) {
6921 args.push_back("--path");
6922 args.push_back(exec_dir);
6923 }
6924
6925 List<String>::Element *vbf = args.find("--verbose");
6926 if (vbf) {
6927 args.erase(vbf);
6928 }
6929 } else {
6930 args.push_back("--path");
6931 args.push_back(ProjectSettings::get_singleton()->get_resource_path());
6932
6933 args.push_back("-e");
6934 }
6935 if (!files_to_delete_on_exit.is_empty()) {
6936 args.push_back("--clear-shader-cache");
6937 }
6938
6939 if (!to_reopen.is_empty()) {
6940 args.push_back(to_reopen);
6941 }
6942
6943 OS::get_singleton()->set_restart_on_exit(true, args);
6944}
6945
6946void EditorNode::_scene_tab_closed(int p_tab) {
6947 current_menu_option = SCENE_TAB_CLOSE;
6948 tab_closing_idx = p_tab;
6949 Node *scene = editor_data.get_edited_scene_root(p_tab);
6950 if (!scene) {
6951 _discard_changes();
6952 return;
6953 }
6954
6955 String scene_filename = scene->get_scene_file_path();
6956 String unsaved_message;
6957
6958 if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(p_tab))) {
6959 if (scene_filename.is_empty()) {
6960 unsaved_message = TTR("This scene was never saved.");
6961 } else {
6962 uint32_t time_opened = editor_data.get_scene_time_opened(p_tab);
6963 unsaved_message = _get_unsaved_scene_dialog_text(scene_filename, time_opened);
6964 }
6965 } else {
6966 // Check if any plugin has unsaved changes in that scene.
6967 for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
6968 unsaved_message = editor_data.get_editor_plugin(i)->get_unsaved_status(scene_filename);
6969 if (!unsaved_message.is_empty()) {
6970 break;
6971 }
6972 }
6973 }
6974
6975 if (!unsaved_message.is_empty()) {
6976 save_confirmation->set_ok_button_text(TTR("Save & Close"));
6977 save_confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before closing?"));
6978 save_confirmation->reset_size();
6979 save_confirmation->popup_centered();
6980 } else {
6981 _discard_changes();
6982 }
6983
6984 save_editor_layout_delayed();
6985 scene_tabs->update_scene_tabs();
6986}
6987
6988void EditorNode::_cancel_close_scene_tab() {
6989 if (_is_closing_editor()) {
6990 tab_closing_menu_option = -1;
6991 }
6992 changing_scene = false;
6993 tabs_to_close.clear();
6994}
6995
6996void EditorNode::_cancel_confirmation() {
6997 stop_project_confirmation = false;
6998 stop_download_confirmation = false;
6999}
7000
7001void EditorNode::_prepare_save_confirmation_popup() {
7002 if (save_confirmation->get_window() != get_last_exclusive_window()) {
7003 save_confirmation->reparent(get_last_exclusive_window());
7004 }
7005}
7006
7007void EditorNode::_toggle_distraction_free_mode() {
7008 if (EDITOR_GET("interface/editor/behavior/separate_distraction_mode")) {
7009 Control *screen = editor_main_screen->get_current_tab_control();
7010 if (screen == ScriptEditor::get_singleton()) {
7011 script_distraction_free = !script_distraction_free;
7012 set_distraction_free_mode(script_distraction_free);
7013 } else {
7014 scene_distraction_free = !scene_distraction_free;
7015 set_distraction_free_mode(scene_distraction_free);
7016 }
7017 } else {
7018 set_distraction_free_mode(distraction_free->is_pressed());
7019 }
7020}
7021
7022void EditorNode::update_distraction_free_mode() {
7023 if (!EDITOR_GET("interface/editor/behavior/separate_distraction_mode")) {
7024 return;
7025 }
7026 Control *screen = editor_main_screen->get_current_tab_control();
7027 if (screen == ScriptEditor::get_singleton()) {
7028 set_distraction_free_mode(script_distraction_free);
7029 } else {
7030 set_distraction_free_mode(scene_distraction_free);
7031 }
7032}
7033
7034void EditorNode::set_distraction_free_mode(bool p_enter) {
7035 distraction_free->set_pressed(p_enter);
7036
7037 if (p_enter) {
7038 if (editor_dock_manager->are_docks_visible()) {
7039 editor_dock_manager->set_docks_visible(false);
7040 }
7041 } else {
7042 editor_dock_manager->set_docks_visible(true);
7043 }
7044
7045 emit_signal(SNAME("distraction_free_mode_changed"), p_enter);
7046}
7047
7048bool EditorNode::is_distraction_free_mode_enabled() const {
7049 return distraction_free->is_pressed();
7050}
7051
7052void EditorNode::update_distraction_free_button_theme() {
7053 if (distraction_free->get_meta("_scene_tabs_owned", true)) {
7054 distraction_free->set_theme_type_variation("FlatMenuButton");
7055 distraction_free->add_theme_style_override(SceneStringName(pressed), theme->get_stylebox(CoreStringName(normal), "FlatMenuButton"));
7056 } else {
7057 distraction_free->set_theme_type_variation("BottomPanelButton");
7058 distraction_free->remove_theme_style_override(SceneStringName(pressed));
7059 }
7060}
7061
7062void EditorNode::set_center_split_offset(int p_offset) {
7063 center_split->set_split_offset(p_offset);
7064}
7065
7066Dictionary EditorNode::drag_resource(const Ref<Resource> &p_res, Control *p_from) {
7067 Control *drag_control = memnew(Control);
7068 TextureRect *drag_preview = memnew(TextureRect);
7069 Label *label = memnew(Label);
7070 label->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
7071 label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
7072
7073 Ref<Texture2D> preview;
7074
7075 {
7076 // TODO: make proper previews
7077 Ref<Texture2D> texture = theme->get_icon(SNAME("FileBigThumb"), EditorStringName(EditorIcons));
7078 if (texture.is_valid()) {
7079 Ref<Image> img = texture->get_image();
7080 img = img->duplicate();
7081 img->resize(48, 48); // meh
7082 preview = ImageTexture::create_from_image(img);
7083 }
7084 }
7085
7086 drag_preview->set_texture(preview);
7087 drag_control->add_child(drag_preview);
7088 if (p_res->get_path().is_resource_file()) {
7089 label->set_text(p_res->get_path().get_file());
7090 } else if (!p_res->get_name().is_empty()) {
7091 label->set_text(p_res->get_name());
7092 } else {
7093 label->set_text(p_res->get_class());
7094 }
7095
7096 drag_control->add_child(label);
7097
7098 p_from->set_drag_preview(drag_control); // Wait until it enters scene.
7099
7100 label->set_position(Point2((preview->get_width() - label->get_minimum_size().width) / 2, preview->get_height()));
7101
7102 Dictionary drag_data;
7103 drag_data["type"] = "resource";
7104 drag_data["resource"] = p_res;
7105 drag_data["from"] = p_from;
7106
7107 return drag_data;
7108}
7109
7110Dictionary EditorNode::drag_files_and_dirs(const Vector<String> &p_paths, Control *p_from) {
7111 bool has_folder = false;
7112 bool has_file = false;
7113 for (int i = 0; i < p_paths.size(); i++) {
7114 bool is_folder = p_paths[i].ends_with("/");
7115 has_folder |= is_folder;
7116 has_file |= !is_folder;
7117 }
7118
7119 int max_rows = 6;
7120 int num_rows = p_paths.size() > max_rows ? max_rows - 1 : p_paths.size(); // Don't waste a row to say "1 more file" - list it instead.
7121 VBoxContainer *vbox = memnew(VBoxContainer);
7122 for (int i = 0; i < num_rows; i++) {
7123 HBoxContainer *hbox = memnew(HBoxContainer);
7124 TextureRect *icon = memnew(TextureRect);
7125 Label *label = memnew(Label);
7126 label->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
7127 label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
7128
7129 if (p_paths[i].ends_with("/")) {
7130 label->set_text(p_paths[i].substr(0, p_paths[i].length() - 1).get_file());
7131 icon->set_texture(theme->get_icon(SNAME("Folder"), EditorStringName(EditorIcons)));
7132 } else {
7133 label->set_text(p_paths[i].get_file());
7134 icon->set_texture(theme->get_icon(SNAME("File"), EditorStringName(EditorIcons)));
7135 }
7136 icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
7137 icon->set_size(Size2(16, 16));
7138 hbox->add_child(icon);
7139 hbox->add_child(label);
7140 vbox->add_child(hbox);
7141 }
7142
7143 if (p_paths.size() > num_rows) {
7144 Label *label = memnew(Label);
7145 label->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
7146 if (has_file && has_folder) {
7147 label->set_text(vformat(TTR("%d more files or folders"), p_paths.size() - num_rows));
7148 } else if (has_folder) {
7149 label->set_text(vformat(TTR("%d more folders"), p_paths.size() - num_rows));
7150 } else {
7151 label->set_text(vformat(TTR("%d more files"), p_paths.size() - num_rows));
7152 }
7153 vbox->add_child(label);
7154 }
7155 p_from->set_drag_preview(vbox); // Wait until it enters scene.
7156
7157 Dictionary drag_data;
7158 drag_data["type"] = has_folder ? "files_and_dirs" : "files";
7159 drag_data["files"] = p_paths;
7160 drag_data["from"] = p_from;
7161 return drag_data;
7162}
7163
7164void EditorNode::add_tool_menu_item(const String &p_name, const Callable &p_callback) {
7165 int idx = tool_menu->get_item_count();
7166 tool_menu->add_item(p_name, TOOLS_CUSTOM);
7167 tool_menu->set_item_metadata(idx, p_callback);
7168}
7169
7170void EditorNode::add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu) {
7171 ERR_FAIL_NULL(p_submenu);
7172 ERR_FAIL_COND(p_submenu->get_parent() != nullptr);
7173 tool_menu->add_submenu_node_item(p_name, p_submenu, TOOLS_CUSTOM);
7174}
7175
7176void EditorNode::remove_tool_menu_item(const String &p_name) {
7177 for (int i = 0; i < tool_menu->get_item_count(); i++) {
7178 if (tool_menu->get_item_id(i) != TOOLS_CUSTOM) {
7179 continue;
7180 }
7181
7182 if (tool_menu->get_item_text(i) == p_name) {
7183 if (tool_menu->get_item_submenu(i) != "") {
7184 Node *n = tool_menu->get_node(tool_menu->get_item_submenu(i));
7185 tool_menu->remove_child(n);
7186 memdelete(n);
7187 }
7188 tool_menu->remove_item(i);
7189 tool_menu->reset_size();
7190 return;
7191 }
7192 }
7193}
7194
7195PopupMenu *EditorNode::get_export_as_menu() {
7196 return export_as_menu;
7197}
7198
7199void EditorNode::_dropped_files(const Vector<String> &p_files) {
7200 String to_path = FileSystemDock::get_singleton()->get_folder_path_at_mouse_position();
7201 if (to_path.is_empty()) {
7202 to_path = FileSystemDock::get_singleton()->get_current_directory();
7203 }
7204 to_path = ProjectSettings::get_singleton()->globalize_path(to_path);
7205
7206 _add_dropped_files_recursive(p_files, to_path);
7207
7208 EditorFileSystem::get_singleton()->scan_changes();
7209}
7210
7211void EditorNode::_add_dropped_files_recursive(const Vector<String> &p_files, String to_path) {
7212 Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
7213 ERR_FAIL_COND(dir.is_null());
7214
7215 for (int i = 0; i < p_files.size(); i++) {
7216 const String &from = p_files[i];
7217 String to = to_path.path_join(from.get_file());
7218
7219 if (dir->dir_exists(from)) {
7220 Vector<String> sub_files;
7221
7222 Ref<DirAccess> sub_dir = DirAccess::open(from);
7223 ERR_FAIL_COND(sub_dir.is_null());
7224
7225 sub_dir->list_dir_begin();
7226
7227 String next_file = sub_dir->get_next();
7228 while (!next_file.is_empty()) {
7229 if (next_file == "." || next_file == "..") {
7230 next_file = sub_dir->get_next();
7231 continue;
7232 }
7233
7234 sub_files.push_back(from.path_join(next_file));
7235 next_file = sub_dir->get_next();
7236 }
7237
7238 if (!sub_files.is_empty()) {
7239 dir->make_dir(to);
7240 _add_dropped_files_recursive(sub_files, to);
7241 }
7242
7243 continue;
7244 }
7245
7246 dir->copy(from, to);
7247 }
7248}
7249
7250void EditorNode::_file_access_close_error_notify(const String &p_str) {
7251 callable_mp_static(&EditorNode::_file_access_close_error_notify_impl).call_deferred(p_str);
7252}
7253
7254void EditorNode::_file_access_close_error_notify_impl(const String &p_str) {
7255 add_io_error(vformat(TTR("Unable to write to file '%s', file in use, locked or lacking permissions."), p_str));
7256}
7257
7258// Recursive function to inform nodes that an array of nodes have had their scene reimported.
7259// It will attempt to call a method named '_nodes_scene_reimported' on every node in the
7260// tree so that editor scripts which create transient nodes will have the opportunity
7261// to recreate them.
7262void EditorNode::_notify_nodes_scene_reimported(Node *p_node, Array p_reimported_nodes) {
7263 Skeleton3D *skel_3d = Object::cast_to<Skeleton3D>(p_node);
7264 if (skel_3d) {
7265 skel_3d->reset_bone_poses();
7266 } else {
7267 BoneAttachment3D *attachment = Object::cast_to<BoneAttachment3D>(p_node);
7268 if (attachment) {
7269 attachment->notify_rebind_required();
7270 }
7271 }
7272
7273 p_node->call(SNAME("_nodes_scene_reimported"), p_reimported_nodes);
7274
7275 for (int i = 0; i < p_node->get_child_count(); i++) {
7276 _notify_nodes_scene_reimported(p_node->get_child(i), p_reimported_nodes);
7277 }
7278}
7279
7280void EditorNode::reload_scene(const String &p_path) {
7281 int scene_idx = -1;
7282
7283 const String lpath = ProjectSettings::get_singleton()->localize_path(p_path);
7284 for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
7285 if (editor_data.get_scene_path(i) == lpath) {
7286 scene_idx = i;
7287 break;
7288 }
7289 }
7290 ERR_FAIL_COND_MSG(scene_idx == -1, vformat("Can't reload scene %s, as it's not opened.", p_path));
7291
7292 int current_tab = editor_data.get_edited_scene();
7293 bool is_current_scene = current_tab == scene_idx;
7294 if (is_current_scene) {
7295 editor_data.apply_changes_in_editors();
7296 }
7297
7298 // Reload scene.
7299 _remove_scene(scene_idx, false);
7300 Error err = load_scene(p_path, true, false, true, false);
7301 if (err != OK) {
7302 return;
7303 }
7304
7305 // Adjust index so tab is back a the previous position.
7306 editor_data.move_scene_to_index(editor_data.get_edited_scene_count() - 1, scene_idx);
7307 EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_scene_history_id(scene_idx), false);
7308
7309 // Recover the current tab.
7310 if (is_current_scene) {
7311 _set_current_scene_nocheck(current_tab, true);
7312 } else {
7313 editor_data.set_edited_scene(current_tab);
7314 scene_tabs->update_scene_tabs();
7315 }
7316}
7317
7318void EditorNode::find_all_instances_inheriting_path_in_node(Node *p_root, Node *p_node, const String &p_instance_path, HashSet<Node *> &p_instance_list) {
7319 bool valid_instance_found = false;
7320
7321 // Attempt to find all the instances matching path we're going to reload.
7322 if (p_node->get_scene_file_path() == p_instance_path) {
7323 valid_instance_found = true;
7324 } else {
7325 Node *current_node = p_node;
7326
7327 Ref<SceneState> inherited_state = current_node->get_scene_inherited_state();
7328 while (inherited_state.is_valid()) {
7329 String inherited_path = inherited_state->get_path();
7330 if (inherited_path == p_instance_path) {
7331 valid_instance_found = true;
7332 break;
7333 }
7334
7335 inherited_state = inherited_state->get_base_scene_state();
7336 }
7337 }
7338
7339 // Instead of adding this instance directly, if its not owned by the scene, walk its ancestors
7340 // and find the first node still owned by the scene. This is what we will reloading instead.
7341 if (valid_instance_found) {
7342 Node *current_node = p_node;
7343 while (true) {
7344 if (current_node->get_owner() == p_root || current_node->get_owner() == nullptr) {
7345 p_instance_list.insert(current_node);
7346 break;
7347 }
7348 current_node = current_node->get_parent();
7349 }
7350 }
7351
7352 for (int i = 0; i < p_node->get_child_count(); i++) {
7353 find_all_instances_inheriting_path_in_node(p_root, p_node->get_child(i), p_instance_path, p_instance_list);
7354 }
7355}
7356
7357void EditorNode::preload_reimporting_with_path_in_edited_scenes(const List<String> &p_scenes) {
7358 EditorProgress progress("preload_reimporting_scene", TTR("Preparing scenes for reload"), editor_data.get_edited_scene_count());
7359
7360 int original_edited_scene_idx = editor_data.get_edited_scene();
7361
7362 // Walk through each opened scene to get a global list of all instances which match
7363 // the current reimported scenes.
7364 for (int current_scene_idx = 0; current_scene_idx < editor_data.get_edited_scene_count(); current_scene_idx++) {
7365 progress.step(vformat(TTR("Analyzing scene %s"), editor_data.get_scene_title(current_scene_idx)), current_scene_idx);
7366
7367 Node *edited_scene_root = editor_data.get_edited_scene_root(current_scene_idx);
7368
7369 if (edited_scene_root) {
7370 SceneModificationsEntry scene_modifications;
7371
7372 for (const String &instance_path : p_scenes) {
7373 if (editor_data.get_scene_path(current_scene_idx) == instance_path) {
7374 continue;
7375 }
7376
7377 HashSet<Node *> instances_to_reimport;
7378 find_all_instances_inheriting_path_in_node(edited_scene_root, edited_scene_root, instance_path, instances_to_reimport);
7379 if (instances_to_reimport.size() > 0) {
7380 editor_data.set_edited_scene(current_scene_idx);
7381
7382 List<Node *> instance_list_with_children;
7383 for (Node *original_node : instances_to_reimport) {
7384 InstanceModificationsEntry instance_modifications;
7385
7386 // Fetching all the modified properties of the nodes reimported scene.
7387 get_preload_scene_modification_table(edited_scene_root, original_node, original_node, instance_modifications);
7388
7389 instance_modifications.original_node = original_node;
7390 instance_modifications.instance_path = instance_path;
7391 scene_modifications.instance_list.push_back(instance_modifications);
7392
7393 instance_list_with_children.push_back(original_node);
7394 get_children_nodes(original_node, instance_list_with_children);
7395 }
7396
7397 // Search the scene to find nodes that references the nodes will be recreated.
7398 get_preload_modifications_reference_to_nodes(edited_scene_root, edited_scene_root, instances_to_reimport, instance_list_with_children, scene_modifications.other_instances_modifications);
7399 }
7400 }
7401
7402 if (scene_modifications.instance_list.size() > 0) {
7403 scenes_modification_table[current_scene_idx] = scene_modifications;
7404 }
7405 }
7406 }
7407
7408 editor_data.set_edited_scene(original_edited_scene_idx);
7409
7410 progress.step(TTR("Preparation done."), editor_data.get_edited_scene_count());
7411}
7412
7413void EditorNode::reload_instances_with_path_in_edited_scenes() {
7414 if (scenes_modification_table.is_empty()) {
7415 return;
7416 }
7417 EditorProgress progress("reloading_scene", TTR("Scenes reloading"), editor_data.get_edited_scene_count());
7418 progress.step(TTR("Reloading..."), 0, true);
7419
7420 Error err;
7421 Array replaced_nodes;
7422 HashMap<String, Ref<PackedScene>> local_scene_cache;
7423
7424 // Reload the new instances.
7425 for (KeyValue<int, SceneModificationsEntry> &scene_modifications_elem : scenes_modification_table) {
7426 for (InstanceModificationsEntry instance_modifications : scene_modifications_elem.value.instance_list) {
7427 if (!local_scene_cache.has(instance_modifications.instance_path)) {
7428 Ref<PackedScene> instance_scene_packed_scene = ResourceLoader::load(instance_modifications.instance_path, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
7429
7430 ERR_FAIL_COND(err != OK);
7431 ERR_FAIL_COND(instance_scene_packed_scene.is_null());
7432
7433 local_scene_cache[instance_modifications.instance_path] = instance_scene_packed_scene;
7434 }
7435 }
7436 }
7437
7438 // Save the current scene state/selection in case of lost.
7439 Dictionary editor_state = _get_main_scene_state();
7440 editor_data.save_edited_scene_state(editor_selection, &editor_history, editor_state);
7441 editor_selection->clear();
7442
7443 int original_edited_scene_idx = editor_data.get_edited_scene();
7444
7445 for (KeyValue<int, SceneModificationsEntry> &scene_modifications_elem : scenes_modification_table) {
7446 // Set the current scene.
7447 int current_scene_idx = scene_modifications_elem.key;
7448 SceneModificationsEntry *scene_modifications = &scene_modifications_elem.value;
7449
7450 editor_data.set_edited_scene(current_scene_idx);
7451 Node *current_edited_scene = editor_data.get_edited_scene_root(current_scene_idx);
7452
7453 // Make sure the node is in the tree so that editor_selection can add node smoothly.
7454 if (original_edited_scene_idx != current_scene_idx) {
7455 // Prevent scene roots with the same name from being in the tree at the same time.
7456 Node *original_edited_scene_root = editor_data.get_edited_scene_root(original_edited_scene_idx);
7457 if (original_edited_scene_root && original_edited_scene_root->get_name() == current_edited_scene->get_name()) {
7458 scene_root->remove_child(original_edited_scene_root);
7459 }
7460 scene_root->add_child(current_edited_scene);
7461 }
7462
7463 // Restore the state so that the selection can be updated.
7464 editor_state = editor_data.restore_edited_scene_state(editor_selection, &editor_history);
7465
7466 int current_history_id = editor_data.get_current_edited_scene_history_id();
7467 bool is_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(current_history_id);
7468
7469 // Clear the history for this affected tab.
7470 EditorUndoRedoManager::get_singleton()->clear_history(current_history_id, false);
7471
7472 // Update the version
7473 editor_data.is_scene_changed(current_scene_idx);
7474
7475 for (InstanceModificationsEntry instance_modifications : scene_modifications->instance_list) {
7476 Node *original_node = instance_modifications.original_node;
7477 String original_node_file_path = original_node->get_scene_file_path();
7478 Ref<PackedScene> instance_scene_packed_scene = local_scene_cache[instance_modifications.instance_path];
7479
7480 // Load a replacement scene for the node.
7481 Ref<PackedScene> current_packed_scene;
7482 Ref<PackedScene> base_packed_scene;
7483 if (original_node_file_path == instance_modifications.instance_path) {
7484 // If the node file name directly matches the scene we're replacing,
7485 // just load it since we already cached it.
7486 current_packed_scene = instance_scene_packed_scene;
7487 } else {
7488 // Otherwise, check the inheritance chain, reloading and caching any scenes
7489 // we require along the way.
7490 List<String> required_load_paths;
7491
7492 // Do we need to check if the paths are empty?
7493 if (!original_node_file_path.is_empty()) {
7494 required_load_paths.push_front(original_node_file_path);
7495 }
7496 Ref<SceneState> inherited_state = original_node->get_scene_inherited_state();
7497 while (inherited_state.is_valid()) {
7498 String inherited_path = inherited_state->get_path();
7499 // Do we need to check if the paths are empty?
7500 if (!inherited_path.is_empty()) {
7501 required_load_paths.push_front(inherited_path);
7502 }
7503 inherited_state = inherited_state->get_base_scene_state();
7504 }
7505
7506 // Ensure the inheritance chain is loaded in the correct order so that cache can
7507 // be properly updated.
7508 for (String path : required_load_paths) {
7509 if (current_packed_scene.is_valid()) {
7510 base_packed_scene = current_packed_scene;
7511 }
7512 if (!local_scene_cache.find(path)) {
7513 current_packed_scene = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
7514 local_scene_cache[path] = current_packed_scene;
7515 } else {
7516 current_packed_scene = local_scene_cache[path];
7517 }
7518 }
7519 }
7520
7521 ERR_FAIL_COND(current_packed_scene.is_null());
7522
7523 // Instantiate early so that caches cleared on load in SceneState can be rebuilt early.
7524 Node *instantiated_node = nullptr;
7525
7526 // If we are in a inherited scene, it's easier to create a new base scene and
7527 // grab the node from there.
7528 // When scene_path_to_node is '.' and we have scene_inherited_state, it's because
7529 // it's a multi-level inheritance scene. We should use
7530 NodePath scene_path_to_node = current_edited_scene->get_path_to(original_node);
7531 Ref<SceneState> scene_state = current_edited_scene->get_scene_inherited_state();
7532 if (String(scene_path_to_node) != "." && scene_state.is_valid() && scene_state->get_path() != instance_modifications.instance_path && scene_state->find_node_by_path(scene_path_to_node) >= 0) {
7533 Node *root_node = scene_state->instantiate(SceneState::GenEditState::GEN_EDIT_STATE_INSTANCE);
7534 instantiated_node = root_node->get_node(scene_path_to_node);
7535
7536 if (instantiated_node) {
7537 if (instantiated_node->get_parent()) {
7538 // Remove from the root so we can delete it from memory.
7539 instantiated_node->get_parent()->remove_child(instantiated_node);
7540 // No need of the additional children that could have been added to the node
7541 // in the base scene. That will be managed by the 'addition_list' later.
7542 _remove_all_not_owned_children(instantiated_node, instantiated_node);
7543 memdelete(root_node);
7544 }
7545 } else {
7546 // Should not happen because we checked with find_node_by_path before, just in case.
7547 memdelete(root_node);
7548 }
7549 }
7550
7551 if (!instantiated_node) {
7552 // If no base scene was found to create the node, we will use the reimported packed scene directly.
7553 // But, when the current edited scene is the reimported scene, it's because it's an inherited scene
7554 // derived from the reimported scene. In that case, we will not instantiate current_packed_scene, because
7555 // we would reinstantiate ourself. Using the base scene is better.
7556 if (current_edited_scene == original_node) {
7557 if (base_packed_scene.is_valid()) {
7558 instantiated_node = base_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
7559 } else {
7560 instantiated_node = instance_scene_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
7561 }
7562 } else {
7563 instantiated_node = current_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
7564 }
7565 }
7566 ERR_FAIL_NULL(instantiated_node);
7567
7568 // Disconnect all relevant connections, all connections from and persistent connections to.
7569 for (const KeyValue<NodePath, ModificationNodeEntry> &modification_table_entry : instance_modifications.modifications) {
7570 for (Connection conn : modification_table_entry.value.connections_from) {
7571 conn.signal.get_object()->disconnect(conn.signal.get_name(), conn.callable);
7572 }
7573 for (ConnectionWithNodePath cwnp : modification_table_entry.value.connections_to) {
7574 Connection conn = cwnp.connection;
7575 if (conn.flags & CONNECT_PERSIST) {
7576 conn.signal.get_object()->disconnect(conn.signal.get_name(), conn.callable);
7577 }
7578 }
7579 }
7580
7581 // Store all the paths for any selected nodes which are ancestors of the node we're replacing.
7582 List<NodePath> selected_node_paths;
7583 for (Node *selected_node : editor_selection->get_top_selected_node_list()) {
7584 if (selected_node == original_node || original_node->is_ancestor_of(selected_node)) {
7585 selected_node_paths.push_back(original_node->get_path_to(selected_node));
7586 editor_selection->remove_node(selected_node);
7587 }
7588 }
7589
7590 // Remove all nodes which were added as additional elements (they will be restored later).
7591 for (AdditiveNodeEntry additive_node_entry : instance_modifications.addition_list) {
7592 Node *addition_node = additive_node_entry.node;
7593 addition_node->get_parent()->remove_child(addition_node);
7594 }
7595
7596 // Clear ownership of the nodes (kind of hack to workaround an issue with
7597 // replace_by when called on nodes in other tabs).
7598 List<Node *> nodes_owned_by_original_node;
7599 original_node->get_owned_by(original_node, &nodes_owned_by_original_node);
7600 for (Node *owned_node : nodes_owned_by_original_node) {
7601 owned_node->set_owner(nullptr);
7602 }
7603
7604 // Replace the old nodes in the history with the new ones.
7605 // Otherwise, the history will contain old nodes, and some could still be
7606 // instantiated if used elsewhere, causing the "current edited item" to be
7607 // linked to a node that will be destroyed later. This caused the editor to
7608 // crash when reimporting scenes with animations when "Editable children" was enabled.
7609 replace_history_reimported_nodes(original_node, instantiated_node, original_node);
7610
7611 // Reset the editable instance state.
7612 HashMap<NodePath, SceneEditorDataEntry> scene_editor_data_table;
7613 Node *owner = original_node->get_owner();
7614 if (!owner) {
7615 owner = original_node;
7616 }
7617
7618 get_scene_editor_data_for_node(owner, original_node, scene_editor_data_table);
7619
7620 // The current node being reloaded may also be an additional node for another node
7621 // that is in the process of being reloaded.
7622 // Replacing the additional node with the new one prevents a crash where nodes
7623 // in 'addition_list' are removed from the scene tree and queued for deletion.
7624 for (InstanceModificationsEntry &im : scene_modifications->instance_list) {
7625 for (AdditiveNodeEntry &additive_node_entry : im.addition_list) {
7626 if (additive_node_entry.node == original_node) {
7627 additive_node_entry.node = instantiated_node;
7628 }
7629 }
7630 }
7631
7632 bool original_node_scene_instance_load_placeholder = original_node->get_scene_instance_load_placeholder();
7633
7634 // Delete all the remaining node children.
7635 while (original_node->get_child_count()) {
7636 Node *child = original_node->get_child(0);
7637
7638 original_node->remove_child(child);
7639 child->queue_free();
7640 }
7641
7642 // Update the name to match
7643 instantiated_node->set_name(original_node->get_name());
7644
7645 // Is this replacing the edited root node?
7646
7647 if (current_edited_scene == original_node) {
7648 // Set the instance as un inherited scene of itself.
7649 instantiated_node->set_scene_inherited_state(instantiated_node->get_scene_instance_state());
7650 instantiated_node->set_scene_instance_state(nullptr);
7651 instantiated_node->set_scene_file_path(original_node_file_path);
7652 current_edited_scene = instantiated_node;
7653 editor_data.set_edited_scene_root(current_edited_scene);
7654
7655 if (original_edited_scene_idx == current_scene_idx) {
7656 // How that the editor executes a redraw while destroying or progressing the EditorProgress,
7657 // it crashes when the root scene has been replaced because the edited scene
7658 // was freed and no longer in the scene tree.
7659 SceneTreeDock::get_singleton()->set_edited_scene(current_edited_scene);
7660 if (get_tree()) {
7661 get_tree()->set_edited_scene_root(current_edited_scene);
7662 }
7663 }
7664 }
7665
7666 // Replace the original node with the instantiated version.
7667 original_node->replace_by(instantiated_node, false);
7668 instantiated_node->set_unique_scene_id(original_node->get_unique_scene_id());
7669
7670 // Mark the old node for deletion.
7671 original_node->queue_free();
7672
7673 // Restore the placeholder state from the original node.
7674 instantiated_node->set_scene_instance_load_placeholder(original_node_scene_instance_load_placeholder);
7675
7676 // Attempt to re-add all the additional nodes.
7677 for (AdditiveNodeEntry additive_node_entry : instance_modifications.addition_list) {
7678 Node *parent_node = instantiated_node->get_node_or_null(additive_node_entry.parent);
7679
7680 if (!parent_node) {
7681 parent_node = current_edited_scene;
7682 }
7683
7684 parent_node->add_child(additive_node_entry.node);
7685 parent_node->move_child(additive_node_entry.node, additive_node_entry.index);
7686 // If the additive node's owner was the node which got replaced, update it.
7687 if (additive_node_entry.owner == original_node) {
7688 additive_node_entry.owner = instantiated_node;
7689 }
7690
7691 additive_node_entry.node->set_owner(additive_node_entry.owner);
7692
7693 // If the parent node was lost, attempt to restore the original global transform.
7694 {
7695 Node2D *node_2d = Object::cast_to<Node2D>(additive_node_entry.node);
7696 if (node_2d) {
7697 node_2d->set_transform(additive_node_entry.transform_2d);
7698 }
7699
7700 Node3D *node_3d = Object::cast_to<Node3D>(additive_node_entry.node);
7701 if (node_3d) {
7702 node_3d->set_transform(additive_node_entry.transform_3d);
7703 }
7704 }
7705 }
7706
7707 // Restore the scene's editable instance and folded states.
7708 for (HashMap<NodePath, SceneEditorDataEntry>::Iterator I = scene_editor_data_table.begin(); I; ++I) {
7709 Node *node = owner->get_node_or_null(I->key);
7710 if (node) {
7711 if (owner != node) {
7712 owner->set_editable_instance(node, I->value.is_editable);
7713 }
7714 node->set_display_folded(I->value.is_display_folded);
7715 }
7716 }
7717
7718 // Restore the selection.
7719 if (selected_node_paths.size()) {
7720 for (NodePath selected_node_path : selected_node_paths) {
7721 Node *selected_node = instantiated_node->get_node_or_null(selected_node_path);
7722 if (selected_node) {
7723 editor_selection->add_node(selected_node);
7724 }
7725 }
7726 editor_selection->update();
7727 }
7728
7729 // Attempt to restore the modified properties and signals for the instantitated node and all its owned children.
7730 for (KeyValue<NodePath, ModificationNodeEntry> &E : instance_modifications.modifications) {
7731 NodePath new_current_path = E.key;
7732 Node *modifiable_node = instantiated_node->get_node_or_null(new_current_path);
7733
7734 update_node_from_node_modification_entry(modifiable_node, E.value);
7735 }
7736 // Add the newly instantiated node to the edited scene's replaced node list.
7737 replaced_nodes.push_back(instantiated_node);
7738 }
7739
7740 // Attempt to restore the modified properties and signals for the instantitated node and all its owned children.
7741 for (KeyValue<NodePath, ModificationNodeEntry> &E : scene_modifications->other_instances_modifications) {
7742 NodePath new_current_path = E.key;
7743 Node *modifiable_node = current_edited_scene->get_node_or_null(new_current_path);
7744
7745 if (modifiable_node) {
7746 update_node_from_node_modification_entry(modifiable_node, E.value);
7747 }
7748 }
7749
7750 if (is_unsaved) {
7751 EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(current_history_id);
7752 }
7753
7754 // Save the current handled scene state.
7755 editor_data.save_edited_scene_state(editor_selection, &editor_history, editor_state);
7756 editor_selection->clear();
7757
7758 // Cleanup the history of the changes.
7759 editor_history.cleanup_history();
7760
7761 if (original_edited_scene_idx != current_scene_idx) {
7762 scene_root->remove_child(current_edited_scene);
7763
7764 // Ensure the current edited scene is re-added if removed earlier because it has the same name
7765 // as the reimported scene. The editor could crash when reloading SceneTreeDock if the current
7766 // edited scene is not in the scene tree.
7767 Node *original_edited_scene_root = editor_data.get_edited_scene_root(original_edited_scene_idx);
7768 if (original_edited_scene_root && !original_edited_scene_root->get_parent()) {
7769 scene_root->add_child(original_edited_scene_root);
7770 }
7771 }
7772 }
7773
7774 // For the whole editor, call the _notify_nodes_scene_reimported with a list of replaced nodes.
7775 // To inform anything that depends on them that they should update as appropriate.
7776 _notify_nodes_scene_reimported(this, replaced_nodes);
7777
7778 editor_data.set_edited_scene(original_edited_scene_idx);
7779
7780 editor_data.restore_edited_scene_state(editor_selection, &editor_history);
7781
7782 progress.step(TTR("Reloading done."), editor_data.get_edited_scene_count());
7783}
7784
7785void EditorNode::_remove_all_not_owned_children(Node *p_node, Node *p_owner) {
7786 Vector<Node *> nodes_to_remove;
7787 if (p_node != p_owner && p_node->get_owner() != p_owner) {
7788 nodes_to_remove.push_back(p_node);
7789 }
7790 for (int i = 0; i < p_node->get_child_count(); i++) {
7791 Node *child_node = p_node->get_child(i);
7792 _remove_all_not_owned_children(child_node, p_owner);
7793 }
7794
7795 for (Node *node : nodes_to_remove) {
7796 node->get_parent()->remove_child(node);
7797 node->queue_free();
7798 }
7799}
7800
7801int EditorNode::plugin_init_callback_count = 0;
7802
7803void EditorNode::add_plugin_init_callback(EditorPluginInitializeCallback p_callback) {
7804 ERR_FAIL_COND(plugin_init_callback_count == MAX_INIT_CALLBACKS);
7805
7806 plugin_init_callbacks[plugin_init_callback_count++] = p_callback;
7807}
7808
7809EditorPluginInitializeCallback EditorNode::plugin_init_callbacks[EditorNode::MAX_INIT_CALLBACKS];
7810
7811int EditorNode::build_callback_count = 0;
7812
7813void EditorNode::add_build_callback(EditorBuildCallback p_callback) {
7814 ERR_FAIL_COND(build_callback_count == MAX_INIT_CALLBACKS);
7815
7816 build_callbacks[build_callback_count++] = p_callback;
7817}
7818
7819EditorBuildCallback EditorNode::build_callbacks[EditorNode::MAX_BUILD_CALLBACKS];
7820
7821bool EditorNode::call_build() {
7822 bool builds_successful = true;
7823
7824 for (int i = 0; i < build_callback_count && builds_successful; i++) {
7825 if (!build_callbacks[i]()) {
7826 ERR_PRINT("A Godot Engine build callback failed.");
7827 builds_successful = false;
7828 }
7829 }
7830
7831 if (builds_successful && !editor_data.call_build()) {
7832 ERR_PRINT("An EditorPlugin build callback failed.");
7833 builds_successful = false;
7834 }
7835
7836 return builds_successful;
7837}
7838
7839void EditorNode::call_run_scene(const String &p_scene, Vector<String> &r_args) {
7840 for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
7841 EditorPlugin *plugin = editor_data.get_editor_plugin(i);
7842 plugin->run_scene(p_scene, r_args);
7843 }
7844}
7845
7846void EditorNode::_inherit_imported(const String &p_action) {
7847 open_imported->hide();
7848 open_scene(open_import_request, true, true);
7849}
7850
7851void EditorNode::_open_imported() {
7852 open_scene(open_import_request, true, false, true);
7853}
7854
7855void EditorNode::dim_editor(bool p_dimming) {
7856 dimmed = p_dimming;
7857 gui_base->set_modulate(p_dimming ? Color(0.5, 0.5, 0.5) : Color(1, 1, 1));
7858}
7859
7860bool EditorNode::is_editor_dimmed() const {
7861 return dimmed;
7862}
7863
7864void EditorNode::open_export_template_manager() {
7865 export_template_manager->popup_manager();
7866}
7867
7868void EditorNode::add_resource_conversion_plugin(const Ref<EditorResourceConversionPlugin> &p_plugin) {
7869 resource_conversion_plugins.push_back(p_plugin);
7870}
7871
7872void EditorNode::remove_resource_conversion_plugin(const Ref<EditorResourceConversionPlugin> &p_plugin) {
7873 resource_conversion_plugins.erase(p_plugin);
7874}
7875
7876Vector<Ref<EditorResourceConversionPlugin>> EditorNode::find_resource_conversion_plugin_for_resource(const Ref<Resource> &p_for_resource) {
7877 if (p_for_resource.is_null()) {
7878 return Vector<Ref<EditorResourceConversionPlugin>>();
7879 }
7880
7881 Vector<Ref<EditorResourceConversionPlugin>> ret;
7882 for (Ref<EditorResourceConversionPlugin> resource_conversion_plugin : resource_conversion_plugins) {
7883 if (resource_conversion_plugin.is_valid() && resource_conversion_plugin->handles(p_for_resource)) {
7884 ret.push_back(resource_conversion_plugin);
7885 }
7886 }
7887
7888 return ret;
7889}
7890
7891Vector<Ref<EditorResourceConversionPlugin>> EditorNode::find_resource_conversion_plugin_for_type_name(const String &p_type) {
7892 Vector<Ref<EditorResourceConversionPlugin>> ret;
7893
7894 if (ClassDB::class_exists(p_type) && ClassDB::can_instantiate(p_type)) {
7895 Ref<Resource> temp = Object::cast_to<Resource>(ClassDB::instantiate(p_type));
7896 if (temp.is_valid()) {
7897 for (Ref<EditorResourceConversionPlugin> resource_conversion_plugin : resource_conversion_plugins) {
7898 if (resource_conversion_plugin.is_valid() && resource_conversion_plugin->handles(temp)) {
7899 ret.push_back(resource_conversion_plugin);
7900 }
7901 }
7902 }
7903 }
7904
7905 return ret;
7906}
7907
7908void EditorNode::_update_renderer_color() {
7909 String rendering_method = renderer->get_selected_metadata();
7910
7911 const Color renderer_normal_color = theme->get_color(rendering_method + "_color", EditorStringName(Editor));
7912 const Color mono_color = theme->get_color(SNAME("mono_color"), EditorStringName(Editor));
7913
7914 renderer->add_theme_color_override(SceneStringName(font_color), renderer_normal_color);
7915 renderer->add_theme_color_override("font_hover_color", renderer_normal_color.lerp(mono_color, 0.3));
7916 renderer->add_theme_color_override("font_pressed_color", renderer_normal_color.lerp(mono_color, 0.4));
7917 renderer->add_theme_color_override("font_hover_pressed_color", renderer_normal_color.lerp(mono_color, 0.5));
7918}
7919
7920void EditorNode::_renderer_selected(int p_index) {
7921 const String rendering_method = renderer->get_item_metadata(p_index);
7922 const String current_renderer = GLOBAL_GET("rendering/renderer/rendering_method");
7923 if (rendering_method == current_renderer) {
7924 return;
7925 }
7926
7927 // Don't change selection.
7928 for (int i = 0; i < renderer->get_item_count(); i++) {
7929 if (renderer->get_item_metadata(i) == current_renderer) {
7930 renderer->select(i);
7931 break;
7932 }
7933 }
7934
7935 if (video_restart_dialog == nullptr) {
7936 video_restart_dialog = memnew(ConfirmationDialog);
7937 video_restart_dialog->set_ok_button_text(TTRC("Save & Restart"));
7938 video_restart_dialog->get_label()->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
7939 gui_base->add_child(video_restart_dialog);
7940 } else {
7941 video_restart_dialog->disconnect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_set_renderer_name_save_and_restart));
7942 }
7943
7944 const String mobile_rendering_method = rendering_method == "forward_plus" ? "mobile" : rendering_method;
7945 const String web_rendering_method = "gl_compatibility";
7946 video_restart_dialog->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_set_renderer_name_save_and_restart).bind(rendering_method));
7947 video_restart_dialog->set_text(
7948 vformat(TTR("Changing the renderer requires restarting the editor.\n\nChoosing Save & Restart will change the renderer to:\n- Desktop platforms: %s\n- Mobile platforms: %s\n- Web platform: %s"),
7949 _to_rendering_method_display_name(rendering_method), _to_rendering_method_display_name(mobile_rendering_method), _to_rendering_method_display_name(web_rendering_method)));
7950 video_restart_dialog->popup_centered();
7951
7952 _update_renderer_color();
7953}
7954
7955String EditorNode::_to_rendering_method_display_name(const String &p_rendering_method) const {
7956 if (p_rendering_method == "forward_plus") {
7957 return TTR("Forward+");
7958 }
7959 if (p_rendering_method == "mobile") {
7960 return TTR("Mobile");
7961 }
7962 if (p_rendering_method == "gl_compatibility") {
7963 return TTR("Compatibility");
7964 }
7965 return p_rendering_method;
7966}
7967
7968void EditorNode::_set_renderer_name_save_and_restart(const String &p_rendering_method) {
7969 ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method", p_rendering_method);
7970
7971 if (p_rendering_method == "mobile" || p_rendering_method == "gl_compatibility") {
7972 // Also change the mobile override if changing to a compatible renderer.
7973 // This prevents visual discrepancies between desktop and mobile platforms.
7974 ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method.mobile", p_rendering_method);
7975 } else if (p_rendering_method == "forward_plus") {
7976 // Use the equivalent mobile renderer. This prevents the renderer from staying
7977 // on its old choice if moving from `gl_compatibility` to `forward_plus`.
7978 ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method.mobile", "mobile");
7979 }
7980
7981 ProjectSettings::get_singleton()->save();
7982
7983 save_all_scenes();
7984 restart_editor();
7985}
7986
7987void EditorNode::_resource_saved(Ref<Resource> p_resource, const String &p_path) {
7988 if (singleton->saving_resources_in_path.has(p_resource)) {
7989 // This is going to be handled by save_resource_in_path when the time is right.
7990 return;
7991 }
7992
7993 if (EditorFileSystem::get_singleton()) {
7994 EditorFileSystem::get_singleton()->update_file(p_path);
7995 }
7996
7997 singleton->editor_folding.save_resource_folding(p_resource, p_path);
7998}
7999
8000void EditorNode::_resource_loaded(Ref<Resource> p_resource, const String &p_path) {
8001 singleton->editor_folding.load_resource_folding(p_resource, p_path);
8002}
8003
8004void EditorNode::_feature_profile_changed() {
8005 Ref<EditorFeatureProfile> profile = feature_profile_manager->get_current_profile();
8006 if (profile.is_valid()) {
8007 editor_dock_manager->set_dock_enabled(SignalsDock::get_singleton(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SIGNALS_DOCK));
8008 editor_dock_manager->set_dock_enabled(GroupsDock::get_singleton(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_GROUPS_DOCK));
8009 // The Import dock is useless without the FileSystem dock. Ensure the configuration is valid.
8010 bool fs_dock_disabled = profile->is_feature_disabled(EditorFeatureProfile::FEATURE_FILESYSTEM_DOCK);
8011 editor_dock_manager->set_dock_enabled(FileSystemDock::get_singleton(), !fs_dock_disabled);
8012 editor_dock_manager->set_dock_enabled(ImportDock::get_singleton(), !fs_dock_disabled && !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_IMPORT_DOCK));
8013 editor_dock_manager->set_dock_enabled(history_dock, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_HISTORY_DOCK));
8014
8015 editor_dock_manager->set_dock_enabled(Node3DEditor::get_singleton(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D));
8016 editor_dock_manager->set_dock_enabled(ScriptEditor::get_singleton(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SCRIPT));
8017 if (!Engine::get_singleton()->is_recovery_mode_hint()) {
8018 editor_dock_manager->set_dock_enabled(GameView::get_dock(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_GAME));
8019 }
8020 if (AssetLibraryEditorPlugin::is_available()) {
8021 editor_dock_manager->set_dock_enabled(AssetLibraryEditorPlugin::get_library(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_ASSET_LIB));
8022 }
8023 } else {
8024 editor_dock_manager->set_dock_enabled(ImportDock::get_singleton(), true);
8025 editor_dock_manager->set_dock_enabled(SignalsDock::get_singleton(), true);
8026 editor_dock_manager->set_dock_enabled(GroupsDock::get_singleton(), true);
8027 editor_dock_manager->set_dock_enabled(FileSystemDock::get_singleton(), true);
8028 editor_dock_manager->set_dock_enabled(history_dock, true);
8029 editor_dock_manager->set_dock_enabled(Node3DEditor::get_singleton(), true);
8030 editor_dock_manager->set_dock_enabled(ScriptEditor::get_singleton(), true);
8031 if (!Engine::get_singleton()->is_recovery_mode_hint() && GameView::get_dock()) {
8032 editor_dock_manager->set_dock_enabled(GameView::get_dock(), true);
8033 }
8034 if (AssetLibraryEditorPlugin::is_available()) {
8035 editor_dock_manager->set_dock_enabled(AssetLibraryEditorPlugin::get_library(), true);
8036 }
8037 }
8038
8039 editor_dock_manager->update_docks_menu();
8040}
8041
8042void EditorNode::_bind_methods() {
8043 ClassDB::bind_method(D_METHOD("push_item", "object", "property", "inspector_only"), &EditorNode::push_item, DEFVAL(""), DEFVAL(false));
8044
8045 ClassDB::bind_method("set_edited_scene", &EditorNode::set_edited_scene);
8046
8047 ClassDB::bind_method("stop_child_process", &EditorNode::stop_child_process);
8048
8049 ClassDB::bind_method(D_METHOD("update_node_reference", "value", "node", "remove"), &EditorNode::update_node_reference, DEFVAL(false));
8050
8051 ADD_SIGNAL(MethodInfo("request_help_search"));
8052 ADD_SIGNAL(MethodInfo("script_add_function_request", PropertyInfo(Variant::OBJECT, "obj"), PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::PACKED_STRING_ARRAY, "args")));
8053 ADD_SIGNAL(MethodInfo("resource_saved", PropertyInfo(Variant::OBJECT, "obj")));
8054 ADD_SIGNAL(MethodInfo("scene_saved", PropertyInfo(Variant::STRING, "path")));
8055 ADD_SIGNAL(MethodInfo("scene_changed"));
8056 ADD_SIGNAL(MethodInfo("scene_closed", PropertyInfo(Variant::STRING, "path")));
8057 ADD_SIGNAL(MethodInfo("preview_locale_changed"));
8058 ADD_SIGNAL(MethodInfo("resource_counter_changed"));
8059 ADD_SIGNAL(MethodInfo("distraction_free_mode_changed", PropertyInfo(Variant::BOOL, "enabled")));
8060}
8061
8062static Node *_resource_get_edited_scene() {
8063 return EditorNode::get_singleton()->get_edited_scene();
8064}
8065
8066void EditorNode::_print_handler(void *p_this, const String &p_string, bool p_error, bool p_rich) {
8067 if (!Thread::is_main_thread()) {
8068 callable_mp_static(&EditorNode::_print_handler_impl).call_deferred(p_string, p_error, p_rich);
8069 } else {
8070 _print_handler_impl(p_string, p_error, p_rich);
8071 }
8072}
8073
8074void EditorNode::_print_handler_impl(const String &p_string, bool p_error, bool p_rich) {
8075 if (!singleton) {
8076 return;
8077 }
8078 if (p_error) {
8079 singleton->log->add_message(p_string, EditorLog::MSG_TYPE_ERROR);
8080 } else if (p_rich) {
8081 singleton->log->add_message(p_string, EditorLog::MSG_TYPE_STD_RICH);
8082 } else {
8083 singleton->log->add_message(p_string, EditorLog::MSG_TYPE_STD);
8084 }
8085}
8086
8087static void _execute_thread(void *p_ud) {
8088 EditorNode::ExecuteThreadArgs *eta = (EditorNode::ExecuteThreadArgs *)p_ud;
8089 Error err = OS::get_singleton()->execute(eta->path, eta->args, &eta->output, &eta->exitcode, true, &eta->execute_output_mutex);
8090 print_verbose("Thread exit status: " + itos(eta->exitcode));
8091 if (err != OK) {
8092 eta->exitcode = err;
8093 }
8094
8095 eta->done.set();
8096}
8097
8098int EditorNode::execute_and_show_output(const String &p_title, const String &p_path, const List<String> &p_arguments, bool p_close_on_ok, bool p_close_on_errors, String *r_output) {
8099 if (execute_output_dialog) {
8100 execute_output_dialog->set_title(p_title);
8101 execute_output_dialog->get_ok_button()->set_disabled(true);
8102 execute_outputs->clear();
8103 execute_outputs->set_scroll_follow(true);
8104 EditorInterface::get_singleton()->popup_dialog_centered_ratio(execute_output_dialog);
8105 }
8106
8107 ExecuteThreadArgs eta;
8108 eta.path = p_path;
8109 eta.args = p_arguments;
8110 eta.exitcode = 255;
8111
8112 int prev_len = 0;
8113
8114 eta.execute_output_thread.start(_execute_thread, &eta);
8115
8116 while (!eta.done.is_set()) {
8117 {
8118 MutexLock lock(eta.execute_output_mutex);
8119 if (prev_len != eta.output.length()) {
8120 String to_add = eta.output.substr(prev_len);
8121 prev_len = eta.output.length();
8122 execute_outputs->add_text(to_add);
8123 DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
8124 Main::iteration();
8125 }
8126 }
8127 OS::get_singleton()->delay_usec(1000);
8128 }
8129
8130 eta.execute_output_thread.wait_to_finish();
8131 execute_outputs->add_text("\nExit Code: " + itos(eta.exitcode));
8132
8133 if (execute_output_dialog) {
8134 if (p_close_on_errors && eta.exitcode != 0) {
8135 execute_output_dialog->hide();
8136 }
8137 if (p_close_on_ok && eta.exitcode == 0) {
8138 execute_output_dialog->hide();
8139 }
8140
8141 execute_output_dialog->get_ok_button()->set_disabled(false);
8142 }
8143
8144 if (r_output) {
8145 *r_output = eta.output;
8146 }
8147 return eta.exitcode;
8148}
8149
8150void EditorNode::set_unfocused_low_processor_usage_mode_enabled(bool p_enabled) {
8151 unfocused_low_processor_usage_mode_enabled = p_enabled;
8152}
8153
8154void EditorNode::_build_file_menu(bool p_dark_mode) {
8155 if (!file_menu) {
8156 return;
8157 }
8158 file_menu->clear(false);
8159
8160 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("CreateNewSceneFrom"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/new_scene"), SCENE_NEW_SCENE);
8161 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/new_inherited_scene"), SCENE_NEW_INHERITED_SCENE);
8162 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("PackedScene"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/open_scene"), SCENE_OPEN_SCENE);
8163 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/reopen_closed_scene"), SCENE_OPEN_PREV);
8164 if (!recent_scenes) {
8165 recent_scenes = memnew(PopupMenu);
8166 recent_scenes->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
8167 recent_scenes->connect("about_to_popup", callable_mp(this, &EditorNode::_update_recent_scenes));
8168 recent_scenes->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_open_recent_scene));
8169 }
8170 file_menu->add_submenu_node_item(TTRC("Open Recent"), recent_scenes, SCENE_OPEN_RECENT);
8171 file_menu->add_separator();
8172
8173 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Save"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/save_scene"), SCENE_SAVE_SCENE);
8174 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_scene_as"), SCENE_SAVE_AS_SCENE);
8175 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_all_scenes"), SCENE_SAVE_ALL_SCENES);
8176 file_menu->add_separator();
8177
8178 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Load"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/quick_open"), SCENE_QUICK_OPEN);
8179 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/quick_open_scene"), SCENE_QUICK_OPEN_SCENE);
8180 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/quick_open_script"), SCENE_QUICK_OPEN_SCRIPT);
8181 file_menu->add_separator();
8182
8183 if (!export_as_menu) {
8184 export_as_menu = memnew(PopupMenu);
8185 export_as_menu->add_shortcut(ED_GET_SHORTCUT("editor/export_as_mesh_library"), FILE_EXPORT_MESH_LIBRARY);
8186 export_as_menu->connect("index_pressed", callable_mp(this, &EditorNode::_export_as_menu_option));
8187 }
8188 file_menu->add_submenu_node_item(TTRC("Export As..."), export_as_menu, SCENE_EXPORT_AS);
8189 file_menu->add_separator();
8190
8191 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("RotateLeft"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("ui_undo"), SCENE_UNDO, false, true);
8192 file_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), SCENE_REDO, false, true);
8193 file_menu->add_separator();
8194
8195 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/reload_saved_scene"), SCENE_RELOAD_SAVED_SCENE);
8196 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("CloseScene"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/close_scene"), SCENE_CLOSE);
8197 file_menu->add_shortcut(ED_GET_SHORTCUT("editor/close_all_scenes"), SCENE_CLOSE_ALL);
8198#ifdef MACOS_ENABLED
8199 if (menu_type != MENU_TYPE_GLOBAL) {
8200 // On macOS "Quit" option is in the "app" menu.
8201 file_menu->add_separator();
8202 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/file_quit"), SCENE_QUIT, true);
8203 }
8204#else
8205 file_menu->add_separator();
8206 file_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/file_quit"), SCENE_QUIT, true);
8207#endif
8208}
8209
8210void EditorNode::_build_project_menu(bool p_dark_mode) {
8211 if (!project_menu) {
8212 return;
8213 }
8214 project_menu->clear(false);
8215
8216 project_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("ClassList"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/project_settings"), PROJECT_OPEN_SETTINGS);
8217 project_menu->add_shortcut(ED_GET_SHORTCUT("editor/find_in_files"), PROJECT_FIND_IN_FILES);
8218 project_menu->add_shortcut(ED_GET_SHORTCUT("editor/replace_in_files"), PROJECT_REPLACE_IN_FILES);
8219 project_menu->add_separator();
8220
8221 project_menu->add_item(TTRC("Version Control"), PROJECT_VERSION_CONTROL);
8222 if (!vcs_actions_menu) {
8223 vcs_actions_menu = VersionControlEditorPlugin::get_singleton()->get_version_control_actions_panel();
8224 vcs_actions_menu->connect("index_pressed", callable_mp(this, &EditorNode::_version_control_menu_option));
8225 vcs_actions_menu->add_item(TTRC("Create/Override Version Control Metadata..."), VCS_METADATA);
8226 vcs_actions_menu->add_item(TTRC("Version Control Settings..."), VCS_SETTINGS);
8227 }
8228 project_menu->set_item_submenu_node(project_menu->get_item_index(PROJECT_VERSION_CONTROL), vcs_actions_menu);
8229
8230 project_menu->add_separator();
8231 project_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("ResourcePreloader"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/export"), PROJECT_EXPORT);
8232#ifndef WEB_ENABLED
8233 // In Web editor "Download Project Source" option is used instead
8234 project_menu->add_item(TTRC("Pack Project as ZIP..."), PROJECT_PACK_AS_ZIP);
8235#endif
8236 project_menu->add_item(TTRC("Setup Android Build..."), PROJECT_SETUP_ANDROID_BUILD);
8237#ifndef ANDROID_ENABLED
8238 project_menu->add_item(TTRC("Open User Data Folder"), PROJECT_OPEN_USER_DATA_FOLDER);
8239#endif
8240 project_menu->add_separator();
8241
8242 if (!tool_menu) {
8243 tool_menu = memnew(PopupMenu);
8244 tool_menu->connect("index_pressed", callable_mp(this, &EditorNode::_tool_menu_option));
8245 tool_menu->add_shortcut(ED_GET_SHORTCUT("editor/orphan_resource_explorer"), TOOLS_ORPHAN_RESOURCES);
8246 tool_menu->add_shortcut(ED_GET_SHORTCUT("editor/engine_compilation_configuration_editor"), TOOLS_BUILD_PROFILE_MANAGER);
8247 tool_menu->add_shortcut(ED_GET_SHORTCUT("editor/upgrade_project"), TOOLS_PROJECT_UPGRADE);
8248 tool_menu->add_shortcut(ED_GET_SHORTCUT("editor/clear_project_cache"), TOOLS_CLEAR_PROJECT_CACHE);
8249 }
8250 project_menu->add_submenu_node_item(TTRC("Tools"), tool_menu);
8251
8252 project_menu->add_separator();
8253#ifdef WEB_ENABLED
8254 project_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Download"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/download_project_source"), PROJECT_DOWNLOAD_SOURCE);
8255#endif
8256 project_menu->add_shortcut(ED_GET_SHORTCUT("editor/reload_current_project"), PROJECT_RELOAD_CURRENT_PROJECT);
8257 project_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Close"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/quit_to_project_list"), PROJECT_QUIT_TO_PROJECT_MANAGER, true);
8258}
8259
8260void EditorNode::_build_settings_menu(bool p_dark_mode) {
8261 if (!settings_menu) {
8262 return;
8263 }
8264 settings_menu->clear(false);
8265
8266#ifdef MACOS_ENABLED
8267 if (menu_type != MENU_TYPE_GLOBAL) {
8268 // On macOS "Settings" option is in the "app" menu.
8269 settings_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/editor_settings"), EDITOR_OPEN_SETTINGS);
8270 }
8271#else
8272 settings_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/editor_settings"), EDITOR_OPEN_SETTINGS);
8273#endif
8274 settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/command_palette"), EDITOR_COMMAND_PALETTE);
8275 settings_menu->add_separator();
8276
8277 settings_menu->add_submenu_node_item(TTRC("Editor Docks"), editor_dock_manager->get_docks_menu());
8278
8279 if (!editor_layouts) {
8280 editor_layouts = memnew(PopupMenu);
8281 editor_layouts->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_layout_menu_option));
8282 }
8283 settings_menu->add_submenu_node_item(TTRC("Editor Layout"), editor_layouts);
8284 settings_menu->add_separator();
8285
8286 settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/take_screenshot"), EDITOR_TAKE_SCREENSHOT);
8287 settings_menu->set_item_tooltip(-1, TTRC("Screenshots are stored in the user data folder (\"user://\")."));
8288
8289 settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/fullscreen_mode"), EDITOR_TOGGLE_FULLSCREEN);
8290 settings_menu->add_separator();
8291
8292#ifndef ANDROID_ENABLED
8293 if (EditorPaths::get_singleton()->get_data_dir() == EditorPaths::get_singleton()->get_config_dir()) {
8294 // Configuration and data folders are located in the same place.
8295 settings_menu->add_item(TTRC("Open Editor Data/Settings Folder"), EDITOR_OPEN_DATA_FOLDER);
8296 } else {
8297 // Separate configuration and data folders.
8298 settings_menu->add_item(TTRC("Open Editor Data Folder"), EDITOR_OPEN_DATA_FOLDER);
8299 settings_menu->add_item(TTRC("Open Editor Settings Folder"), EDITOR_OPEN_CONFIG_FOLDER);
8300 }
8301 settings_menu->add_separator();
8302#endif
8303
8304 settings_menu->add_item(TTRC("Manage Editor Features..."), EDITOR_MANAGE_FEATURE_PROFILES);
8305 settings_menu->add_item(TTRC("Manage Export Templates..."), EDITOR_MANAGE_EXPORT_TEMPLATES);
8306#if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
8307 settings_menu->add_item(TTRC("Configure FBX Importer..."), EDITOR_CONFIGURE_FBX_IMPORTER);
8308#endif
8309}
8310
8311void EditorNode::_build_help_menu(bool p_dark_mode) {
8312 if (!help_menu) {
8313 return;
8314 }
8315 help_menu->clear(false);
8316
8317 if (menu_type == MENU_TYPE_GLOBAL && NativeMenu::get_singleton()->has_system_menu(NativeMenu::HELP_MENU_ID)) {
8318 help_menu->set_system_menu(NativeMenu::HELP_MENU_ID);
8319 } else {
8320 help_menu->set_system_menu(NativeMenu::INVALID_MENU_ID);
8321 }
8322
8323 help_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("HelpSearch"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/editor_help"), HELP_SEARCH);
8324 help_menu->add_separator();
8325 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/online_docs"), HELP_DOCS);
8326 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/forum"), HELP_FORUM);
8327 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/community"), HELP_COMMUNITY);
8328 help_menu->add_separator();
8329 help_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("ActionCopy"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/copy_system_info"), HELP_COPY_SYSTEM_INFO);
8330 help_menu->set_item_tooltip(-1, TTRC("Copies the system info as a single-line text into the clipboard."));
8331 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/report_a_bug"), HELP_REPORT_A_BUG);
8332 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/suggest_a_feature"), HELP_SUGGEST_A_FEATURE);
8333 help_menu->add_shortcut(ED_GET_SHORTCUT("editor/send_docs_feedback"), HELP_SEND_DOCS_FEEDBACK);
8334 help_menu->add_separator();
8335#ifdef MACOS_ENABLED
8336 if (menu_type != MENU_TYPE_GLOBAL) {
8337 // On macOS "About" option is in the "app" menu.
8338 help_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Godot"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/about"), HELP_ABOUT);
8339 }
8340#else
8341 help_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Godot"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/about"), HELP_ABOUT);
8342#endif
8343 help_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Heart"), menu_type == MENU_TYPE_GLOBAL, p_dark_mode), ED_GET_SHORTCUT("editor/support_development"), HELP_SUPPORT_GODOT_DEVELOPMENT);
8344}
8345
8346void EditorNode::_add_to_main_menu(const String &p_name, PopupMenu *p_menu) {
8347 p_menu->set_name(p_name);
8348 main_menu_items.push_back(p_menu);
8349}
8350
8351void EditorNode::_update_main_menu_type() {
8352 bool can_expand = bool(EDITOR_GET("interface/editor/appearance/expand_to_title")) && DisplayServer::get_singleton()->has_feature(DisplayServerEnums::FEATURE_EXTEND_TO_TITLE);
8353 bool use_menu_button = EDITOR_GET("interface/editor/appearance/collapse_main_menu");
8354 bool global_menu = !bool(EDITOR_GET("interface/editor/appearance/use_embedded_menu")) && NativeMenu::get_singleton()->has_feature(NativeMenu::FEATURE_GLOBAL_MENU);
8355 MenuType new_menu_type;
8356 if (global_menu) {
8357 new_menu_type = MENU_TYPE_GLOBAL;
8358 } else if (use_menu_button) {
8359 new_menu_type = MENU_TYPE_COMPACT;
8360 } else {
8361 new_menu_type = MENU_TYPE_FULL;
8362 }
8363
8364 if (new_menu_type == menu_type) {
8365 return; // Nothing to do.
8366 }
8367 menu_type = new_menu_type;
8368
8369 // Update menu items.
8370 bool dark_mode = DisplayServer::get_singleton()->is_dark_mode_supported() && DisplayServer::get_singleton()->is_dark_mode();
8371 _build_file_menu(dark_mode);
8372 _build_project_menu(dark_mode);
8373 _build_settings_menu(dark_mode);
8374 _build_help_menu(dark_mode);
8375
8376 // Delete all menu.
8377 if (main_menu_bar) {
8378 for (PopupMenu *menu : main_menu_items) {
8379 if (menu->get_parent() == main_menu_bar) {
8380 main_menu_bar->remove_child(menu);
8381 }
8382 }
8383 memdelete(main_menu_bar);
8384 main_menu_bar = nullptr;
8385 }
8386 if (main_menu_button) {
8387 PopupMenu *popup = main_menu_button->get_popup();
8388 popup->clear(false);
8389 for (PopupMenu *menu : main_menu_items) {
8390 if (menu->get_parent() == popup) {
8391 popup->remove_child(menu);
8392 }
8393 }
8394 memdelete(main_menu_button);
8395 main_menu_button = nullptr;
8396 }
8397 memdelete(menu_btn_spacer);
8398 menu_btn_spacer = nullptr;
8399
8400 // Create new menu.
8401 if (new_menu_type == MENU_TYPE_COMPACT) {
8402 main_menu_button = memnew(MenuButton);
8403 main_menu_button->set_text(TTRC("Main Menu"));
8404 main_menu_button->set_theme_type_variation("MainScreenButton");
8405 main_menu_button->set_focus_mode(Control::FOCUS_NONE);
8406 if (is_inside_tree()) {
8407 main_menu_button->set_button_icon(theme->get_icon(SNAME("TripleBar"), EditorStringName(EditorIcons)));
8408 }
8409 main_menu_button->set_switch_on_hover(true);
8410
8411 for (PopupMenu *menu : main_menu_items) {
8412 if (menu != apple_menu) {
8413 main_menu_button->get_popup()->add_submenu_node_item(menu->get_name(), menu);
8414 }
8415 }
8416
8417#ifdef ANDROID_ENABLED
8418 // Align main menu icon visually with TouchActionsPanel buttons.
8419 menu_btn_spacer = memnew(Control);
8420 menu_btn_spacer->set_custom_minimum_size(Vector2(8, 0) * EDSCALE);
8421 title_bar->add_child(menu_btn_spacer);
8422 title_bar->move_child(menu_btn_spacer, left_menu_spacer ? left_menu_spacer->get_index() + 1 : 0);
8423#endif
8424 title_bar->add_child(main_menu_button);
8425 if (menu_btn_spacer == nullptr) {
8426 title_bar->move_child(main_menu_button, left_menu_spacer ? left_menu_spacer->get_index() + 1 : 0);
8427 } else {
8428 title_bar->move_child(main_menu_button, menu_btn_spacer->get_index() + 1);
8429 }
8430 } else {
8431 main_menu_bar = memnew(MenuBar);
8432 main_menu_bar->set_mouse_filter(Control::MOUSE_FILTER_STOP);
8433 main_menu_bar->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
8434 main_menu_bar->set_theme_type_variation("MainMenuBar");
8435 main_menu_bar->set_start_index(0); // Main menu, add to the start of global menu.
8436 main_menu_bar->set_prefer_global_menu(menu_type == MENU_TYPE_GLOBAL);
8437 main_menu_bar->set_switch_on_hover(true);
8438
8439 for (PopupMenu *menu : main_menu_items) {
8440 if (menu != apple_menu || menu_type == MENU_TYPE_GLOBAL) {
8441 main_menu_bar->add_child(menu);
8442 }
8443 }
8444
8445 title_bar->add_child(main_menu_bar);
8446 title_bar->move_child(main_menu_bar, left_menu_spacer ? left_menu_spacer->get_index() + 1 : 0);
8447 }
8448
8449 // Show/hide project title.
8450 if (project_title) {
8451 project_title->set_visible(can_expand && menu_type == MENU_TYPE_GLOBAL);
8452 }
8453}
8454
8455void EditorNode::_bottom_panel_resized() {
8456 bottom_panel->set_bottom_panel_offset(center_split->get_split_offset());
8457}
8458
8459#ifdef ANDROID_ENABLED
8460void EditorNode::_touch_actions_panel_mode_changed() {
8461 int panel_mode = EDITOR_GET("interface/touchscreen/touch_actions_panel");
8462 switch (panel_mode) {
8463 case 1: // Embedded
8464 if (touch_actions_panel != nullptr) {
8465 touch_actions_panel->queue_free();
8466 }
8467 touch_actions_panel = memnew(TouchActionsPanel(false));
8468 main_box->call_deferred("add_child", touch_actions_panel);
8469 break;
8470 case 2: // Floating
8471 if (touch_actions_panel != nullptr) {
8472 touch_actions_panel->queue_free();
8473 }
8474 touch_actions_panel = memnew(TouchActionsPanel(true));
8475 call_deferred("add_child", touch_actions_panel);
8476 break;
8477 case 0: // Disabled
8478 if (touch_actions_panel != nullptr) {
8479 touch_actions_panel->queue_free();
8480 touch_actions_panel = nullptr;
8481 }
8482 break;
8483 }
8484}
8485
8486void EditorNode::_screen_orientation_changed(int p_new_orientation) {
8487 portrait_mode = p_new_orientation == DisplayServerEnums::SENSOR_ORIENTATION_PORTRAIT;
8488 vk_spacer->set_custom_minimum_size(Size2()); // Reset size.
8489}
8490#endif
8491
8492#ifdef MACOS_ENABLED
8493extern "C" GameViewPluginBase *get_game_view_plugin();
8494#else
8495GameViewPluginBase *get_game_view_plugin() {
8496 return memnew(GameViewPlugin);
8497}
8498#endif
8499
8500void EditorNode::open_setting_override(const String &p_property) {
8501 editor_settings_dialog->hide();
8502 project_settings_editor->popup_for_override(p_property);
8503}
8504
8505void EditorNode::notify_settings_overrides_changed() {
8506 settings_overrides_changed = true;
8507}
8508
8509// Returns the list of project settings to add to new projects. This is used by the
8510// project manager creation dialog, but also applies to empty `project.godot` files
8511// to cover the command line workflow of creating projects using `touch project.godot`.
8512//
8513// This is used to set better defaults for new projects without affecting existing projects.
8514// Keep the list alphabetically sorted.
8515HashMap<String, Variant> EditorNode::get_initial_settings() {
8516 HashMap<String, Variant> settings;
8517 settings["display/window/stretch/aspect"] = "expand";
8518 settings["display/window/stretch/mode"] = "canvas_items";
8519 settings["gui/common/auto_focus_strategy"] = Control::AutoFocusStrategy::STRATEGY_BALLOON;
8520 settings["input_devices/joypads/ignore_joypad_on_unfocused_application"] = true;
8521 settings["physics/3d/physics_engine"] = PhysicsServer3DManager::JOLT_PHYSICS_NAME;
8522 settings["rendering/rendering_device/driver.windows"] = "d3d12";
8523 settings["rendering/lights_and_shadows/multi_bounce_occlusion/enabled"] = true;
8524 return settings;
8525}
8526
8527EditorNode::EditorNode() {
8528 DEV_ASSERT(!singleton);
8529 singleton = this;
8530
8531 // Detecting headless mode, that means the editor is running in command line.
8532 cmdline_mode = (DisplayServer::get_singleton()->get_name() == "headless");
8533
8534 Resource::_get_local_scene_func = _resource_get_edited_scene;
8535
8536 {
8537 PortableCompressedTexture2D::set_keep_all_compressed_buffers(true);
8538 RenderingServer::get_singleton()->set_debug_generate_wireframes(true);
8539
8540 AudioServer::get_singleton()->set_enable_tagging_used_audio_streams(true);
8541
8542 // No navigation by default if in editor.
8543 if (NavigationServer3D::get_singleton()->get_debug_enabled()) {
8544 NavigationServer3D::get_singleton()->set_active(true);
8545 } else {
8546 NavigationServer3D::get_singleton()->set_active(false);
8547 }
8548
8549 // No physics by default if in editor.
8550#ifndef PHYSICS_3D_DISABLED
8551 PhysicsServer3D::get_singleton()->set_active(false);
8552#endif // PHYSICS_3D_DISABLED
8553#ifndef PHYSICS_2D_DISABLED
8554 PhysicsServer2D::get_singleton()->set_active(false);
8555#endif // PHYSICS_2D_DISABLED
8556
8557 // No scripting by default if in editor (except for tool).
8558 ScriptServer::set_scripting_enabled(false);
8559
8560 if (!DisplayServer::get_singleton()->is_touchscreen_available()) {
8561 // Only if no touchscreen ui hint, disable emulation just in case.
8562 Input::get_singleton()->set_emulate_touch_from_mouse(false);
8563 }
8564 if (DisplayServer::get_singleton()->has_feature(DisplayServerEnums::FEATURE_CUSTOM_CURSOR_SHAPE)) {
8565 DisplayServer::get_singleton()->cursor_set_custom_image(Ref<Resource>());
8566 }
8567 }
8568
8569 SceneState::set_disable_placeholders(true);
8570 ResourceLoader::clear_translation_remaps(); // Using no remaps if in editor.
8571 ResourceLoader::set_create_missing_resources_if_class_unavailable(true);
8572
8573 EditorPropertyNameProcessor *epnp = memnew(EditorPropertyNameProcessor);
8574 add_child(epnp);
8575
8576 EditorUndoRedoManager::get_singleton()->connect("version_changed", callable_mp(this, &EditorNode::_update_undo_redo_allowed));
8577 EditorUndoRedoManager::get_singleton()->connect("version_changed", callable_mp(this, &EditorNode::_update_unsaved_cache));
8578 EditorUndoRedoManager::get_singleton()->connect("history_changed", callable_mp(this, &EditorNode::_update_undo_redo_allowed));
8579 EditorUndoRedoManager::get_singleton()->connect("history_changed", callable_mp(this, &EditorNode::_update_unsaved_cache));
8580 ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &EditorNode::_update_from_settings));
8581 GDExtensionManager::get_singleton()->connect("extensions_reloaded", callable_mp(this, &EditorNode::_gdextensions_reloaded));
8582
8583 Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_main_domain();
8584 domain->set_enabled(false);
8585 domain->set_locale_override(TranslationServer::get_singleton()->get_fallback_locale());
8586
8587 // Load settings.
8588 if (!EditorSettings::get_singleton()) {
8589 EditorSettings::create();
8590 }
8591
8592 ED_SHORTCUT("editor/lock_selected_nodes", TTRC("Lock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::L);
8593 ED_SHORTCUT("editor/unlock_selected_nodes", TTRC("Unlock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::L);
8594 ED_SHORTCUT("editor/group_selected_nodes", TTRC("Group Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::G);
8595 ED_SHORTCUT("editor/ungroup_selected_nodes", TTRC("Ungroup Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::G);
8596 ED_SHORTCUT("editor/toggle_selected_nodes_visibility", TTRC("Toggle Selected Node(s) Visibility"), Key::H);
8597
8598 FileAccess::set_backup_save(EDITOR_GET("filesystem/on_save/safe_save_on_backup_then_rename"));
8599
8600 _update_vsync_mode();
8601
8602 // Warm up the project upgrade tool as early as possible.
8603 project_upgrade_tool = memnew(ProjectUpgradeTool);
8604 run_project_upgrade_tool = EditorSettings::get_singleton()->get_project_metadata(project_upgrade_tool->META_PROJECT_UPGRADE_TOOL, project_upgrade_tool->META_RUN_ON_RESTART, false);
8605 if (run_project_upgrade_tool) {
8606 project_upgrade_tool->begin_upgrade();
8607 }
8608
8609 {
8610 bool agile_input_event_flushing = EDITOR_GET("input/buffering/agile_event_flushing");
8611 bool use_accumulated_input = EDITOR_GET("input/buffering/use_accumulated_input");
8612
8613 Input::get_singleton()->set_agile_input_event_flushing(agile_input_event_flushing);
8614 Input::get_singleton()->set_use_accumulated_input(use_accumulated_input);
8615 }
8616
8617 {
8618 int display_scale = EDITOR_GET("interface/editor/appearance/display_scale");
8619
8620 switch (display_scale) {
8621 case 0:
8622 // Try applying a suitable display scale automatically.
8623 EditorScale::set_scale(EditorSettings::get_auto_display_scale());
8624 break;
8625 case 1:
8626 EditorScale::set_scale(0.75);
8627 break;
8628 case 2:
8629 EditorScale::set_scale(1.0);
8630 break;
8631 case 3:
8632 EditorScale::set_scale(1.25);
8633 break;
8634 case 4:
8635 EditorScale::set_scale(1.5);
8636 break;
8637 case 5:
8638 EditorScale::set_scale(1.75);
8639 break;
8640 case 6:
8641 EditorScale::set_scale(2.0);
8642 break;
8643 default:
8644 EditorScale::set_scale(EDITOR_GET("interface/editor/appearance/custom_display_scale"));
8645 break;
8646 }
8647 }
8648
8649 // Define a minimum window size to prevent UI elements from overlapping or being cut off.
8650 Window *w = Object::cast_to<Window>(SceneTree::get_singleton()->get_root());
8651 if (w) {
8652 const Size2 display_size = DisplayServer::get_singleton()->screen_get_usable_rect(DisplayServerEnums::SCREEN_OF_MAIN_WINDOW).size;
8653 const real_t smallest_display_dimension = display_size.width < display_size.height ? display_size.width : display_size.height;
8654 const Size2 editor_minimum_size = Size2(1024, 600) * EDSCALE;
8655 // Ensure the minimum size is not larger than the display size to avoid issues on smaller screens.
8656 const Size2 computed_minimum_size = editor_minimum_size.minf(smallest_display_dimension);
8657 w->set_min_size(computed_minimum_size); // Calling it this early doesn't sync the property with DS.
8658 DisplayServer::get_singleton()->window_set_min_size(computed_minimum_size);
8659 }
8660
8661 FileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files"));
8662 FileDialog::set_default_display_mode(EDITOR_GET("filesystem/file_dialog/display_mode"));
8663
8664 int swap_cancel_ok = EDITOR_GET("interface/editor/appearance/accept_dialog_cancel_ok_buttons");
8665 if (swap_cancel_ok != 0) { // 0 is auto, set in register_scene based on DisplayServer.
8666 // Swap on means OK first.
8667 AcceptDialog::set_swap_cancel_ok(swap_cancel_ok == 2);
8668 }
8669
8670 int ed_root_dir = EDITOR_GET("interface/editor/localization/ui_layout_direction");
8671 Control::set_root_layout_direction(ed_root_dir);
8672 Window::set_root_layout_direction(ed_root_dir);
8673
8674 ResourceLoader::set_abort_on_missing_resources(false);
8675 ResourceLoader::set_error_notify_func(&EditorNode::add_io_error);
8676 ResourceLoader::set_dependency_error_notify_func(&EditorNode::_dependency_error_report);
8677
8678 SceneState::set_instantiation_warning_notify_func([](const String &p_warning) {
8679 add_io_warning(p_warning);
8680 callable_mp(EditorInterface::get_singleton(), &EditorInterface::mark_scene_as_unsaved).call_deferred();
8681 });
8682
8683 {
8684 // Register importers at the beginning, so dialogs are created with the right extensions.
8685 Ref<ResourceImporterTexture> import_texture;
8686 import_texture.instantiate(true);
8687 ResourceFormatImporter::get_singleton()->add_importer(import_texture);
8688
8689 Ref<ResourceImporterStreamedTexture> import_streamed_texture;
8690 import_streamed_texture.instantiate(true);
8691 ResourceFormatImporter::get_singleton()->add_importer(import_streamed_texture);
8692
8693 Ref<ResourceImporterLayeredTexture> import_cubemap;
8694 import_cubemap.instantiate();
8695 import_cubemap->set_mode(ResourceImporterLayeredTexture::MODE_CUBEMAP);
8696 ResourceFormatImporter::get_singleton()->add_importer(import_cubemap);
8697
8698 Ref<ResourceImporterLayeredTexture> import_array;
8699 import_array.instantiate();
8700 import_array->set_mode(ResourceImporterLayeredTexture::MODE_2D_ARRAY);
8701 ResourceFormatImporter::get_singleton()->add_importer(import_array);
8702
8703 Ref<ResourceImporterLayeredTexture> import_cubemap_array;
8704 import_cubemap_array.instantiate();
8705 import_cubemap_array->set_mode(ResourceImporterLayeredTexture::MODE_CUBEMAP_ARRAY);
8706 ResourceFormatImporter::get_singleton()->add_importer(import_cubemap_array);
8707
8708 Ref<ResourceImporterLayeredTexture> import_3d = memnew(ResourceImporterLayeredTexture(true));
8709 import_3d->set_mode(ResourceImporterLayeredTexture::MODE_3D);
8710 ResourceFormatImporter::get_singleton()->add_importer(import_3d);
8711
8712 Ref<ResourceImporterImage> import_image;
8713 import_image.instantiate();
8714 ResourceFormatImporter::get_singleton()->add_importer(import_image);
8715
8716 Ref<ResourceImporterSVG> import_svg;
8717 import_svg.instantiate();
8718 ResourceFormatImporter::get_singleton()->add_importer(import_svg);
8719
8720 Ref<ResourceImporterTextureAtlas> import_texture_atlas;
8721 import_texture_atlas.instantiate();
8722 ResourceFormatImporter::get_singleton()->add_importer(import_texture_atlas);
8723
8724 Ref<ResourceImporterDynamicFont> import_font_data_dynamic;
8725 import_font_data_dynamic.instantiate();
8726 ResourceFormatImporter::get_singleton()->add_importer(import_font_data_dynamic);
8727
8728 Ref<ResourceImporterBMFont> import_font_data_bmfont;
8729 import_font_data_bmfont.instantiate();
8730 ResourceFormatImporter::get_singleton()->add_importer(import_font_data_bmfont);
8731
8732 Ref<ResourceImporterImageFont> import_font_data_image;
8733 import_font_data_image.instantiate();
8734 ResourceFormatImporter::get_singleton()->add_importer(import_font_data_image);
8735
8736 Ref<ResourceImporterCSVTranslation> import_csv_translation;
8737 import_csv_translation.instantiate();
8738 ResourceFormatImporter::get_singleton()->add_importer(import_csv_translation);
8739
8740 Ref<ResourceImporterWAV> import_wav;
8741 import_wav.instantiate();
8742 ResourceFormatImporter::get_singleton()->add_importer(import_wav);
8743
8744 Ref<ResourceImporterShaderFile> import_shader_file;
8745 import_shader_file.instantiate();
8746 ResourceFormatImporter::get_singleton()->add_importer(import_shader_file);
8747
8748 Ref<ResourceImporterOBJ> import_obj;
8749 import_obj.instantiate();
8750 ResourceFormatImporter::get_singleton()->add_importer(import_obj);
8751
8752 Ref<ResourceImporterScene> import_model_as_scene;
8753 import_model_as_scene.instantiate("PackedScene");
8754 ResourceFormatImporter::get_singleton()->add_importer(import_model_as_scene);
8755
8756 Ref<ResourceImporterScene> import_model_as_animation;
8757 import_model_as_animation.instantiate("AnimationLibrary");
8758 ResourceFormatImporter::get_singleton()->add_importer(import_model_as_animation);
8759
8760 Ref<ResourceImporterScene> import_scene_as_mesh_library = memnew(ResourceImporterScene("MeshLibrary"));
8761 ResourceFormatImporter::get_singleton()->add_importer(import_scene_as_mesh_library);
8762
8763 Ref<ResourceImporterScene> import_scene_as_single_mesh = memnew(ResourceImporterScene("ArrayMesh"));
8764 ResourceFormatImporter::get_singleton()->add_importer(import_scene_as_single_mesh);
8765
8766 {
8767 Ref<EditorSceneFormatImporterCollada> import_collada;
8768 import_collada.instantiate();
8769 ResourceImporterScene::add_scene_importer(import_collada);
8770
8771 Ref<EditorOBJImporter> import_obj2;
8772 import_obj2.instantiate();
8773 ResourceImporterScene::add_scene_importer(import_obj2);
8774
8775 Ref<EditorSceneFormatImporterESCN> import_escn;
8776 import_escn.instantiate();
8777 ResourceImporterScene::add_scene_importer(import_escn);
8778 }
8779
8780 Ref<ResourceImporterBitMap> import_bitmap;
8781 import_bitmap.instantiate();
8782 ResourceFormatImporter::get_singleton()->add_importer(import_bitmap);
8783 }
8784
8785 {
8786 Ref<EditorInspectorDefaultPlugin> eidp;
8787 eidp.instantiate();
8788 EditorInspector::add_inspector_plugin(eidp);
8789
8790 Ref<EditorInspectorRootMotionPlugin> rmp;
8791 rmp.instantiate();
8792 EditorInspector::add_inspector_plugin(rmp);
8793
8794 Ref<EditorInspectorParticleProcessMaterialPlugin> ppm;
8795 ppm.instantiate();
8796 EditorInspector::add_inspector_plugin(ppm);
8797
8798 Ref<EditorInspectorPluginAudioStreamWAV> plugin;
8799 plugin.instantiate();
8800 EditorInspector::add_inspector_plugin(plugin);
8801 }
8802
8803 editor_selection = memnew(EditorSelection);
8804
8805 EditorFileSystem *efs = memnew(EditorFileSystem);
8806 add_child(efs);
8807
8808 EditorContextMenuPluginManager::create();
8809
8810 // Used for previews.
8811 FileDialog::set_get_icon_callback(callable_mp_static(_file_dialog_get_icon));
8812 FileDialog::set_get_thumbnail_callback(callable_mp_static(_file_dialog_get_thumbnail));
8813 FileDialog::register_func = _file_dialog_register;
8814 FileDialog::unregister_func = _file_dialog_unregister;
8815
8816 editor_export = memnew(EditorExport);
8817 add_child(editor_export);
8818
8819 // Exporters might need the theme.
8820 EditorThemeManager::initialize();
8821 theme = EditorThemeManager::generate_theme();
8822 DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), EditorStringName(Editor)));
8823
8824 EDITOR_DEF("_export_preset_advanced_mode", false); // Could be accessed in EditorExportPreset.
8825
8826 register_exporters();
8827
8828 ED_SHORTCUT("canvas_item_editor/pan_view", TTRC("Pan View"), Key::SPACE);
8829
8830 const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
8831 for (const String &E : textfile_ext) {
8832 textfile_extensions.insert(E);
8833 }
8834 const Vector<String> other_file_ext = ((String)(EDITOR_GET("docks/filesystem/other_file_extensions"))).split(",", false);
8835 for (const String &E : other_file_ext) {
8836 other_file_extensions.insert(E);
8837 }
8838
8839 force_textfile_extensions.insert("csv"); // CSV translation source, has `Translation` resource type, but not loadable as resource.
8840
8841 resource_preview = memnew(EditorResourcePreview);
8842 add_child(resource_preview);
8843 progress_dialog = memnew(ProgressDialog);
8844 add_child(progress_dialog);
8845 progress_dialog->connect(SceneStringName(visibility_changed), callable_mp(this, &EditorNode::_progress_dialog_visibility_changed));
8846
8847 gui_base = memnew(Panel);
8848 add_child(gui_base);
8849
8850 icon_manager = memnew(EditorIconManager);
8851 gui_base->add_child(icon_manager);
8852
8853 // Take up all screen.
8854 gui_base->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
8855 gui_base->set_anchor(SIDE_RIGHT, Control::ANCHOR_END);
8856 gui_base->set_anchor(SIDE_BOTTOM, Control::ANCHOR_END);
8857 gui_base->set_end(Point2(0, 0));
8858
8859 main_vbox = memnew(VBoxContainer);
8860
8861#ifdef ANDROID_ENABLED
8862 base_vbox = memnew(VBoxContainer);
8863 base_vbox->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT, Control::PRESET_MODE_MINSIZE, theme->get_constant(SNAME("window_border_margin"), EditorStringName(Editor)));
8864
8865 title_bar = memnew(EditorTitleBar);
8866 base_vbox->add_child(title_bar);
8867
8868 main_box = memnew(BoxContainer);
8869 main_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
8870 main_box->set_v_size_flags(Control::SIZE_EXPAND_FILL);
8871 main_vbox->set_h_size_flags(Control::SIZE_EXPAND_FILL);
8872 main_vbox->set_v_size_flags(Control::SIZE_EXPAND_FILL);
8873 main_box->add_child(main_vbox);
8874 base_vbox->add_child(main_box);
8875
8876 _touch_actions_panel_mode_changed();
8877
8878 vk_spacer = memnew(Control);
8879 base_vbox->add_child(vk_spacer);
8880
8881 gui_base->add_child(base_vbox);
8882#else
8883 gui_base->add_child(main_vbox);
8884
8885 title_bar = memnew(EditorTitleBar);
8886 main_vbox->add_child(title_bar);
8887#endif
8888
8889 DockSplitContainer *main_vsplit = memnew(DockSplitContainer);
8890 main_vsplit->set_name("DockVSplitMain");
8891 main_vsplit->set_vertical(true);
8892 main_vsplit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
8893 main_vbox->add_child(main_vsplit);
8894
8895 main_hsplit = memnew(DockSplitContainer);
8896 main_hsplit->set_name("DockHSplitMain");
8897 main_hsplit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
8898 main_vsplit->add_child(main_hsplit);
8899
8900 left_l_vsplit = memnew(DockSplitContainer);
8901 left_l_vsplit->set_name("DockVSplitLeftL");
8902 left_l_vsplit->set_vertical(true);
8903 main_hsplit->add_child(left_l_vsplit);
8904
8905 LocalVector<DockTabContainer *> dock_slots;
8906 {
8907 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_LEFT_UL, Rect2i(0, 0, 1, 3)));
8908 dock_container->set_name("DockSlotLeftUL");
8909 dock_container->add_margin_valid_drop(SIDE_RIGHT, EditorDock::DOCK_SLOT_LEFT_UR);
8910 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_LEFT_BL);
8911 left_l_vsplit->add_child(dock_container);
8912 dock_slots.push_back(dock_container);
8913 }
8914 {
8915 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_LEFT_BL, Rect2i(0, 3, 1, 3)));
8916 dock_container->set_name("DockSlotLeftBL");
8917 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_LEFT_UL);
8918 dock_container->add_margin_valid_drop(SIDE_RIGHT, EditorDock::DOCK_SLOT_LEFT_BR);
8919 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_BOTTOM_L);
8920 left_l_vsplit->add_child(dock_container);
8921 dock_slots.push_back(dock_container);
8922 }
8923
8924 left_r_vsplit = memnew(DockSplitContainer);
8925 left_r_vsplit->set_name("DockVSplitLeftR");
8926 left_r_vsplit->set_vertical(true);
8927 main_hsplit->add_child(left_r_vsplit);
8928 {
8929 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_LEFT_UR, Rect2i(1, 0, 1, 3)));
8930 dock_container->set_name("DockSlotLeftUR");
8931 dock_container->add_margin_valid_drop(SIDE_LEFT, EditorDock::DOCK_SLOT_LEFT_UL);
8932 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_LEFT_BR);
8933 left_r_vsplit->add_child(dock_container);
8934 dock_slots.push_back(dock_container);
8935 }
8936 {
8937 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_LEFT_BR, Rect2i(1, 3, 1, 3)));
8938 dock_container->set_name("DockSlotLeftBR");
8939 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_LEFT_UR);
8940 dock_container->add_margin_valid_drop(SIDE_LEFT, EditorDock::DOCK_SLOT_LEFT_BL);
8941 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_BOTTOM_L);
8942 left_r_vsplit->add_child(dock_container);
8943 dock_slots.push_back(dock_container);
8944 }
8945
8946 VBoxContainer *center_vb = memnew(VBoxContainer);
8947 center_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
8948 main_hsplit->add_child(center_vb);
8949
8950 center_split = memnew(DockSplitContainer);
8951 center_split->set_name("DockVSplitCenter");
8952 center_split->set_vertical(true);
8953 center_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
8954 center_split->set_collapsed(true);
8955 center_vb->add_child(center_split);
8956 center_split->connect("drag_ended", callable_mp(this, &EditorNode::_bottom_panel_resized));
8957
8958 right_l_vsplit = memnew(DockSplitContainer);
8959 right_l_vsplit->set_name("DockVSplitRightL");
8960 right_l_vsplit->set_vertical(true);
8961 main_hsplit->add_child(right_l_vsplit);
8962 {
8963 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_RIGHT_UL, Rect2i(6, 0, 1, 3)));
8964 dock_container->set_name("DockSlotRightUL");
8965 dock_container->add_margin_valid_drop(SIDE_RIGHT, EditorDock::DOCK_SLOT_RIGHT_UR);
8966 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_RIGHT_BL);
8967 right_l_vsplit->add_child(dock_container);
8968 dock_slots.push_back(dock_container);
8969 }
8970 {
8971 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_RIGHT_BL, Rect2i(6, 3, 1, 3)));
8972 dock_container->set_name("DockSlotRightBL");
8973 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_RIGHT_UL);
8974 dock_container->add_margin_valid_drop(SIDE_RIGHT, EditorDock::DOCK_SLOT_RIGHT_BR);
8975 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_BOTTOM_R);
8976 right_l_vsplit->add_child(dock_container);
8977 dock_slots.push_back(dock_container);
8978 }
8979
8980 right_r_vsplit = memnew(DockSplitContainer);
8981 right_r_vsplit->set_name("DockVSplitRightR");
8982 right_r_vsplit->set_vertical(true);
8983 main_hsplit->add_child(right_r_vsplit);
8984 {
8985 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_RIGHT_UR, Rect2i(7, 0, 1, 3)));
8986 dock_container->set_name("DockSlotRightUR");
8987 dock_container->add_margin_valid_drop(SIDE_LEFT, EditorDock::DOCK_SLOT_RIGHT_UL);
8988 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_RIGHT_BR);
8989 right_r_vsplit->add_child(dock_container);
8990 dock_slots.push_back(dock_container);
8991 }
8992 {
8993 DockTabContainer *dock_container = memnew(SideDockTabContainer(EditorDock::DOCK_SLOT_RIGHT_BR, Rect2i(7, 3, 1, 3)));
8994 dock_container->set_name("DockSlotRightBR");
8995 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_RIGHT_UR);
8996 dock_container->add_margin_valid_drop(SIDE_LEFT, EditorDock::DOCK_SLOT_RIGHT_BL);
8997 dock_container->add_margin_valid_drop(SIDE_BOTTOM, EditorDock::DOCK_SLOT_BOTTOM_R);
8998 right_r_vsplit->add_child(dock_container);
8999 dock_slots.push_back(dock_container);
9000 }
9001
9002 DockSplitContainer *bottom_hsplit = memnew(DockSplitContainer);
9003 bottom_hsplit->set_name("DockHSplitBottom");
9004 main_vsplit->add_child(bottom_hsplit);
9005 {
9006 DockTabContainer *dock_container = memnew(BottomSideDockTabContainer(EditorDock::DOCK_SLOT_BOTTOM_L, Rect2i(0, 6, 4, 2)));
9007 dock_container->set_name("DockSlotBottomL");
9008 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_LEFT_BL);
9009 dock_container->add_margin_valid_drop(SIDE_RIGHT, EditorDock::DOCK_SLOT_BOTTOM_R);
9010 bottom_hsplit->add_child(dock_container);
9011 dock_slots.push_back(dock_container);
9012 }
9013 {
9014 DockTabContainer *dock_container = memnew(BottomSideDockTabContainer(EditorDock::DOCK_SLOT_BOTTOM_R, Rect2i(4, 6, 4, 2)));
9015 dock_container->set_name("DockSlotBottomR");
9016 dock_container->add_margin_valid_drop(SIDE_TOP, EditorDock::DOCK_SLOT_RIGHT_BR);
9017 dock_container->add_margin_valid_drop(SIDE_LEFT, EditorDock::DOCK_SLOT_BOTTOM_L);
9018 bottom_hsplit->add_child(dock_container);
9019 dock_slots.push_back(dock_container);
9020 }
9021
9022 editor_dock_manager = memnew(EditorDockManager);
9023
9024 // Save the splits for easier access.
9025 editor_dock_manager->add_vsplit(left_l_vsplit);
9026 editor_dock_manager->add_vsplit(left_r_vsplit);
9027 editor_dock_manager->add_vsplit(right_l_vsplit);
9028 editor_dock_manager->add_vsplit(right_r_vsplit);
9029
9030 editor_dock_manager->set_main_vsplit(main_vsplit);
9031 editor_dock_manager->set_main_hsplit(main_hsplit);
9032 editor_dock_manager->set_bottom_hsplit(bottom_hsplit);
9033
9034 for (DockTabContainer *dock_container : dock_slots) {
9035 editor_dock_manager->register_dock_slot(dock_container);
9036 }
9037
9038 editor_layout_save_delay_timer = memnew(Timer);
9039 add_child(editor_layout_save_delay_timer);
9040 editor_layout_save_delay_timer->set_wait_time(0.5);
9041 editor_layout_save_delay_timer->set_one_shot(true);
9042 editor_layout_save_delay_timer->connect("timeout", callable_mp(this, &EditorNode::_save_editor_layout));
9043
9044 scan_changes_timer = memnew(Timer);
9045 scan_changes_timer->set_wait_time(0.5);
9046 scan_changes_timer->set_autostart(EDITOR_GET("interface/editor/behavior/import_resources_when_unfocused"));
9047 scan_changes_timer->connect("timeout", callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::scan_changes));
9048 add_child(scan_changes_timer);
9049
9050 top_split = memnew(VSplitContainer);
9051 center_split->add_child(top_split);
9052 top_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
9053 top_split->set_collapsed(true);
9054
9055 VBoxContainer *srt = memnew(VBoxContainer);
9056 srt->set_v_size_flags(Control::SIZE_EXPAND_FILL);
9057 srt->add_theme_constant_override("separation", 0);
9058 top_split->add_child(srt);
9059
9060 scene_tabs = memnew(EditorSceneTabs);
9061 srt->add_child(scene_tabs);
9062 scene_tabs->connect("tab_changed", callable_mp(this, &EditorNode::_set_current_scene));
9063 scene_tabs->connect("tab_closed", callable_mp(this, &EditorNode::_scene_tab_closed));
9064
9065 distraction_free = memnew(Button);
9066 distraction_free->set_theme_type_variation("FlatMenuButton");
9067 ED_SHORTCUT_AND_COMMAND("editor/distraction_free_mode", TTRC("Distraction Free Mode"), KeyModifierMask::CTRL | KeyModifierMask::SHIFT | Key::F11);
9068 ED_SHORTCUT_OVERRIDE("editor/distraction_free_mode", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::D);
9069 ED_SHORTCUT_AND_COMMAND("editor/toggle_last_opened_bottom_panel", TTRC("Toggle Last Opened Bottom Panel"), KeyModifierMask::CMD_OR_CTRL | Key::J);
9070 distraction_free->set_shortcut(ED_GET_SHORTCUT("editor/distraction_free_mode"));
9071 distraction_free->set_tooltip_text(TTRC("Toggle distraction-free mode."));
9072 distraction_free->set_toggle_mode(true);
9073 scene_tabs->add_extra_button(distraction_free);
9074 distraction_free->connect(SceneStringName(pressed), callable_mp(this, &EditorNode::_toggle_distraction_free_mode));
9075
9076 editor_main_screen = memnew(EditorMainScreen);
9077 srt->add_child(editor_main_screen);
9078 title_bar->set_center_control(editor_main_screen->get_internal_container());
9079
9080 editor_dock_manager->register_dock_slot(editor_main_screen);
9081
9082 scene_root = memnew(SubViewport);
9083 scene_root->set_auto_translate_mode(AUTO_TRANSLATE_MODE_ALWAYS);
9084 scene_root->set_translation_domain(StringName());
9085 scene_root->set_embedding_subwindows(true);
9086 scene_root->set_disable_3d(true);
9087 scene_root->set_disable_input(true);
9088 scene_root->set_as_audio_listener_2d(true);
9089
9090 save_accept = memnew(AcceptDialog);
9091 save_accept->set_unparent_when_invisible(true);
9092 save_accept->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind((int)MenuOptions::SCENE_SAVE_AS_SCENE));
9093
9094 project_export = memnew(ProjectExportDialog);
9095 gui_base->add_child(project_export);
9096
9097 dependency_error = memnew(DependencyErrorDialog);
9098 gui_base->add_child(dependency_error);
9099
9100 editor_settings_dialog = memnew(EditorSettingsDialog);
9101 gui_base->add_child(editor_settings_dialog);
9102 editor_settings_dialog->connect("restart_requested", callable_mp(this, &EditorNode::restart_editor).bind(false));
9103
9104 project_settings_editor = memnew(ProjectSettingsEditor(&editor_data));
9105 gui_base->add_child(project_settings_editor);
9106
9107 scene_import_settings = memnew(SceneImportSettingsDialog);
9108 gui_base->add_child(scene_import_settings);
9109
9110 audio_stream_import_settings = memnew(AudioStreamImportSettingsDialog);
9111 gui_base->add_child(audio_stream_import_settings);
9112
9113 fontdata_import_settings = memnew(DynamicFontImportSettingsDialog);
9114 gui_base->add_child(fontdata_import_settings);
9115
9116 export_template_manager = memnew(ExportTemplateManager);
9117 gui_base->add_child(export_template_manager);
9118
9119 feature_profile_manager = memnew(EditorFeatureProfileManager);
9120 gui_base->add_child(feature_profile_manager);
9121
9122 build_profile_manager = memnew(EditorBuildProfileManager);
9123 gui_base->add_child(build_profile_manager);
9124
9125 feature_profile_manager->connect("current_feature_profile_changed", callable_mp(this, &EditorNode::_feature_profile_changed));
9126
9127#if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
9128 fbx_importer_manager = memnew(FBXImporterManager);
9129 gui_base->add_child(fbx_importer_manager);
9130#endif
9131
9132#ifndef ANDROID_ENABLED
9133 android_sdk_manager = memnew(AndroidSDKManager);
9134 gui_base->add_child(android_sdk_manager);
9135#endif
9136
9137 warning = memnew(AcceptDialog);
9138 warning->set_unparent_when_invisible(true);
9139 warning->add_button(TTRC("Copy Text"), true, "copy");
9140 warning->connect("custom_action", callable_mp(this, &EditorNode::_copy_warning));
9141
9142 clear_cache_dialog = memnew(ConfirmationDialog);
9143 clear_cache_dialog->set_autowrap(true);
9144 clear_cache_dialog->set_text(TTRC("Clear all caches for the current project, including the cache for imported assets, exported assets, shaders, UIDs, scripts, and scene groups. New caches will be built upon restarting or exporting the project.\n\nNote that clearing the cache is almost always a workaround for a bug. If you can consistently reproduce the invalid cache or unexpected behavior that is solved by clearing the cache, please report this bug (\"Help > Report a Bug\") with reproduction steps."));
9145 clear_cache_dialog->set_ok_button_text(TTRC("Clear & Restart"));
9146 clear_cache_dialog->get_label()->set_custom_minimum_size(Vector2(600 * EDSCALE, 0));
9147 gui_base->add_child(clear_cache_dialog);
9148 clear_cache_dialog->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_clear_cache_confirmed));
9149
9150 // Command palette and editor shortcuts.
9151 command_palette = EditorCommandPalette::get_singleton();
9152 command_palette->set_title(TTR("Command Palette"));
9153 gui_base->add_child(command_palette);
9154
9155 ED_SHORTCUT("editor/next_tab", TTRC("Next Scene Tab"), KeyModifierMask::CTRL + Key::TAB);
9156 ED_SHORTCUT("editor/prev_tab", TTRC("Previous Scene Tab"), KeyModifierMask::CTRL + KeyModifierMask::SHIFT + Key::TAB);
9157 ED_SHORTCUT("editor/filter_files", TTRC("Focus FileSystem Filter"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::ALT + Key::P);
9158
9159 ED_SHORTCUT_AND_COMMAND("editor/new_scene", TTRC("New Scene"), KeyModifierMask::CMD_OR_CTRL + Key::N);
9160 ED_SHORTCUT_AND_COMMAND("editor/new_inherited_scene", TTRC("New Inherited Scene..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::N);
9161 ED_SHORTCUT_AND_COMMAND("editor/open_scene", TTRC("Open Scene..."), KeyModifierMask::CMD_OR_CTRL + Key::O);
9162 ED_SHORTCUT_AND_COMMAND("editor/reopen_closed_scene", TTRC("Reopen Closed Scene"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::T);
9163
9164 ED_SHORTCUT_AND_COMMAND("editor/save_scene", TTRC("Save Scene"), KeyModifierMask::CMD_OR_CTRL + Key::S);
9165 ED_SHORTCUT_AND_COMMAND("editor/save_scene_as", TTRC("Save Scene As..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::S);
9166 ED_SHORTCUT_AND_COMMAND("editor/save_all_scenes", TTRC("Save All Scenes"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::S);
9167
9168 ED_SHORTCUT_ARRAY_AND_COMMAND("editor/quick_open", TTRC("Quick Open..."), { int32_t(KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::O), int32_t(KeyModifierMask::CMD_OR_CTRL + Key::P) });
9169 ED_SHORTCUT_OVERRIDE_ARRAY("editor/quick_open", "macos", { int32_t(KeyModifierMask::META + KeyModifierMask::CTRL + Key::O), int32_t(KeyModifierMask::CMD_OR_CTRL + Key::P) });
9170 ED_SHORTCUT_AND_COMMAND("editor/quick_open_scene", TTRC("Quick Open Scene..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::O);
9171 ED_SHORTCUT_AND_COMMAND("editor/quick_open_script", TTRC("Quick Open Script..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::ALT + Key::O);
9172
9173 ED_SHORTCUT("editor/export_as_mesh_library", TTRC("MeshLibrary..."));
9174
9175 ED_SHORTCUT_AND_COMMAND("editor/reload_saved_scene", TTRC("Reload Saved Scene"));
9176 ED_SHORTCUT_AND_COMMAND("editor/close_scene", TTRC("Close Scene"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::W);
9177 ED_SHORTCUT_AND_COMMAND("editor/close_all_scenes", TTRC("Close All Scenes"));
9178 ED_SHORTCUT_OVERRIDE("editor/close_scene", "macos", KeyModifierMask::CMD_OR_CTRL + Key::W);
9179
9180 ED_SHORTCUT_AND_COMMAND("editor/editor_settings", TTRC("Editor Settings..."), KeyModifierMask::CMD_OR_CTRL + Key::COMMA);
9181
9182 ED_SHORTCUT_AND_COMMAND("editor/file_quit", TTRC("Quit"), KeyModifierMask::CMD_OR_CTRL + Key::Q);
9183
9184 ED_SHORTCUT_AND_COMMAND("editor/project_settings", TTRC("Project Settings..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::COMMA, TTRC("Project Settings"));
9185 ED_SHORTCUT_AND_COMMAND("editor/find_in_files", TTRC("Find in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::F);
9186 ED_SHORTCUT_AND_COMMAND("editor/replace_in_files", TTRC("Replace in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::R);
9187
9188 ED_SHORTCUT_AND_COMMAND("editor/export", TTRC("Export..."), Key::NONE, TTRC("Export"));
9189
9190 ED_SHORTCUT_AND_COMMAND("editor/orphan_resource_explorer", TTRC("Orphan Resource Explorer..."));
9191 ED_SHORTCUT_AND_COMMAND("editor/engine_compilation_configuration_editor", TTRC("Engine Compilation Configuration Editor..."));
9192 ED_SHORTCUT_AND_COMMAND("editor/upgrade_project", TTRC("Upgrade Project Files..."));
9193 ED_SHORTCUT_AND_COMMAND("editor/clear_project_cache", TTRC("Clear Project Cache..."));
9194
9195#ifdef WEB_ENABLED
9196 ED_SHORTCUT_AND_COMMAND("editor/download_project_source", TTRC("Download Project"));
9197#endif
9198
9199 ED_SHORTCUT_AND_COMMAND("editor/reload_current_project", TTRC("Reload Current Project"));
9200 ED_SHORTCUT_AND_COMMAND("editor/quit_to_project_list", TTRC("Quit to Project List"), KeyModifierMask::CTRL + KeyModifierMask::SHIFT + Key::Q);
9201 ED_SHORTCUT_OVERRIDE("editor/quit_to_project_list", "macos", KeyModifierMask::META + KeyModifierMask::CTRL + KeyModifierMask::ALT + Key::Q);
9202
9203 ED_SHORTCUT("editor/command_palette", TTRC("Command Palette..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::P);
9204
9205 ED_SHORTCUT_AND_COMMAND("editor/take_screenshot", TTRC("Take Screenshot"), KeyModifierMask::CTRL | Key::F12);
9206 ED_SHORTCUT_OVERRIDE("editor/take_screenshot", "macos", KeyModifierMask::META | Key::F12);
9207
9208 ED_SHORTCUT_AND_COMMAND("editor/fullscreen_mode", TTRC("Toggle Fullscreen"), KeyModifierMask::SHIFT | Key::F11);
9209 ED_SHORTCUT_OVERRIDE("editor/fullscreen_mode", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::F);
9210
9211 ED_SHORTCUT_AND_COMMAND("editor/editor_help", TTRC("Search Help..."), Key::F1);
9212 ED_SHORTCUT_OVERRIDE("editor/editor_help", "macos", KeyModifierMask::ALT | Key::SPACE);
9213 ED_SHORTCUT_AND_COMMAND("editor/online_docs", TTRC("Online Documentation"));
9214 ED_SHORTCUT_AND_COMMAND("editor/forum", TTRC("Forum"));
9215 ED_SHORTCUT_AND_COMMAND("editor/community", TTRC("Community"));
9216
9217 ED_SHORTCUT_AND_COMMAND("editor/copy_system_info", TTRC("Copy System Info"));
9218 ED_SHORTCUT_AND_COMMAND("editor/report_a_bug", TTRC("Report a Bug"));
9219 ED_SHORTCUT_AND_COMMAND("editor/suggest_a_feature", TTRC("Suggest a Feature"));
9220 ED_SHORTCUT_AND_COMMAND("editor/send_docs_feedback", TTRC("Send Docs Feedback"));
9221 ED_SHORTCUT_AND_COMMAND("editor/about", TTRC("About Godot..."));
9222 ED_SHORTCUT_AND_COMMAND("editor/support_development", TTRC("Support Godot Development"));
9223
9224 // Use the Ctrl modifier so F2 can be used to rename nodes in the scene tree dock.
9225 ED_SHORTCUT_AND_COMMAND("editor/editor_2d", TTRC("Open 2D Workspace"), KeyModifierMask::CTRL | Key::F1);
9226 ED_SHORTCUT_AND_COMMAND("editor/editor_3d", TTRC("Open 3D Workspace"), KeyModifierMask::CTRL | Key::F2);
9227 ED_SHORTCUT_AND_COMMAND("editor/editor_script", TTRC("Open Script Editor"), KeyModifierMask::CTRL | Key::F3);
9228 ED_SHORTCUT_AND_COMMAND("editor/editor_game", TTRC("Open Game View"), KeyModifierMask::CTRL | Key::F4);
9229 ED_SHORTCUT_AND_COMMAND("editor/editor_asset_store", TTRC("Open Asset Store"), KeyModifierMask::CTRL | Key::F5);
9230
9231 ED_SHORTCUT_OVERRIDE("editor/editor_2d", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_1);
9232 ED_SHORTCUT_OVERRIDE("editor/editor_3d", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_2);
9233 ED_SHORTCUT_OVERRIDE("editor/editor_script", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_3);
9234 ED_SHORTCUT_OVERRIDE("editor/editor_game", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_4);
9235 ED_SHORTCUT_OVERRIDE("editor/editor_asset_store", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_5);
9236
9237 ED_SHORTCUT_AND_COMMAND("editor/editor_next", TTRC("Open the next Editor"));
9238 ED_SHORTCUT_AND_COMMAND("editor/editor_prev", TTRC("Open the previous Editor"));
9239
9240 // Editor menu and toolbar.
9241 bool can_expand = bool(EDITOR_GET("interface/editor/appearance/expand_to_title")) && DisplayServer::get_singleton()->has_feature(DisplayServerEnums::FEATURE_EXTEND_TO_TITLE);
9242
9243#ifdef MACOS_ENABLED
9244 if (NativeMenu::get_singleton()->has_system_menu(NativeMenu::APPLICATION_MENU_ID)) {
9245 apple_menu = memnew(PopupMenu);
9246 apple_menu->set_system_menu(NativeMenu::APPLICATION_MENU_ID);
9247 _add_to_main_menu("Apple", apple_menu);
9248
9249 apple_menu->add_icon_shortcut(get_editor_theme_native_menu_icon(SNAME("Tools"), menu_type == MENU_TYPE_GLOBAL, DisplayServer::get_singleton()->is_dark_mode_supported() && DisplayServer::get_singleton()->is_dark_mode()), ED_GET_SHORTCUT("editor/editor_settings"), EDITOR_OPEN_SETTINGS);
9250 apple_menu->add_separator();
9251 apple_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9252 }
9253#endif
9254
9255 if (can_expand) {
9256 // Add spacer to avoid other controls under window minimize/maximize/close buttons (left side).
9257 left_menu_spacer = memnew(Control);
9258 left_menu_spacer->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
9259 title_bar->add_child(left_menu_spacer);
9260 }
9261
9262 file_menu = memnew(PopupMenu);
9263 file_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9264 file_menu->connect("about_to_popup", callable_mp(this, &EditorNode::_update_file_menu_opened));
9265 _add_to_main_menu(TTRC("Scene"), file_menu);
9266
9267 project_menu = memnew(PopupMenu);
9268 project_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9269 _add_to_main_menu(TTRC("Project"), project_menu);
9270
9271 debug_menu = memnew(PopupMenu);
9272 // Options are added and handled by DebuggerEditorPlugin, do not rebuild.
9273 _add_to_main_menu(TTRC("Debug"), debug_menu);
9274
9275 settings_menu = memnew(PopupMenu);
9276 settings_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9277 _add_to_main_menu(TTRC("Editor"), settings_menu);
9278
9279 help_menu = memnew(PopupMenu);
9280 help_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9281 _add_to_main_menu(TTRC("Help"), help_menu);
9282
9283 _update_main_menu_type();
9284
9285 // Spacer to center 2D / 3D / Script buttons.
9286 left_spacer = memnew(HBoxContainer);
9287 left_spacer->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
9288 left_spacer->set_h_size_flags(Control::SIZE_EXPAND_FILL);
9289 title_bar->add_child(left_spacer);
9290
9291 project_title = memnew(Label);
9292 project_title->add_theme_font_override(SceneStringName(font), theme->get_font(SNAME("bold"), EditorStringName(EditorFonts)));
9293 project_title->add_theme_font_size_override(SceneStringName(font_size), theme->get_font_size(SNAME("bold_size"), EditorStringName(EditorFonts)));
9294 project_title->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
9295 project_title->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
9296 project_title->set_h_size_flags(Control::SIZE_EXPAND_FILL);
9297 project_title->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
9298 project_title->set_visible(can_expand && menu_type == MENU_TYPE_GLOBAL);
9299 left_spacer->add_child(project_title);
9300
9301 // Spacer to center 2D / 3D / Script buttons.
9302 right_spacer = memnew(Control);
9303 right_spacer->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
9304 right_spacer->set_h_size_flags(Control::SIZE_EXPAND_FILL);
9305 title_bar->add_child(right_spacer);
9306
9307 project_run_bar = memnew(EditorRunBar);
9308 project_run_bar->set_mouse_filter(Control::MOUSE_FILTER_STOP);
9309 title_bar->add_child(project_run_bar);
9310 project_run_bar->connect("play_pressed", callable_mp(this, &EditorNode::_project_run_started));
9311 project_run_bar->connect("stop_pressed", callable_mp(this, &EditorNode::_project_run_stopped));
9312
9313 right_menu_hb = memnew(HBoxContainer);
9314 right_menu_hb->set_mouse_filter(Control::MOUSE_FILTER_STOP);
9315 title_bar->add_child(right_menu_hb);
9316
9317 title_bar->move_child(editor_main_screen->get_internal_container(), left_spacer->get_index());
9318
9319 renderer = memnew(OptionButton);
9320 renderer->set_flat(true);
9321 renderer->set_theme_type_variation("TopBarOptionButton");
9322 renderer->set_fit_to_longest_item(false);
9323 renderer->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
9324 renderer->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
9325 renderer->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_ALWAYS);
9326 renderer->set_tooltip_text(TTRC("Choose a renderer.\n\nNotes:\n- On mobile platforms, the Mobile renderer is used if Forward+ is selected here.\n- On the web platform, the Compatibility renderer is always used."));
9327 renderer->set_accessibility_name(TTRC("Renderer"));
9328
9329 right_menu_hb->add_child(renderer);
9330
9331 if (can_expand) {
9332 // Add spacer to avoid other controls under the window minimize/maximize/close buttons (right side).
9333 right_menu_spacer = memnew(Control);
9334 right_menu_spacer->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
9335 title_bar->add_child(right_menu_spacer);
9336 }
9337
9338 const String current_renderer_ps = String(GLOBAL_GET("rendering/renderer/rendering_method")).to_lower();
9339 const String current_renderer_os = OS::get_singleton()->get_current_rendering_method().to_lower();
9340
9341 // Add the renderers name to the UI.
9342 if (current_renderer_ps == current_renderer_os) {
9343 renderer->connect(SceneStringName(item_selected), callable_mp(this, &EditorNode::_renderer_selected));
9344 // As we are doing string comparisons, keep in standard case to prevent problems with capitals
9345 // "vulkan" in particular uses lowercase "v" in the code, and uppercase in the UI.
9346 PackedStringArray renderers = ProjectSettings::get_singleton()->get_custom_property_info().get(StringName("rendering/renderer/rendering_method")).hint_string.split(",", false);
9347 for (int i = 0; i < renderers.size(); i++) {
9348 const String rendering_method = renderers[i].to_lower();
9349 if (rendering_method == "dummy") {
9350 continue;
9351 }
9352 renderer->add_item(String()); // Set in NOTIFICATION_TRANSLATION_CHANGED.
9353 renderer->set_item_metadata(-1, rendering_method);
9354 if (current_renderer_ps == rendering_method) {
9355 renderer->select(i);
9356 }
9357 }
9358 } else {
9359 // It's an CLI-overridden rendering method.
9360 renderer->add_item(String()); // Set in NOTIFICATION_TRANSLATION_CHANGED.
9361 renderer->set_item_metadata(-1, current_renderer_os);
9362 }
9363 _update_renderer_color();
9364
9365 renderer->set_visible(EDITOR_GET("interface/editor/appearance/show_renderer_selector"));
9366
9367 progress_hb = memnew(BackgroundProgress);
9368
9369 layout_dialog = memnew(EditorLayoutsDialog);
9370 gui_base->add_child(layout_dialog);
9371 layout_dialog->set_hide_on_ok(false);
9372 layout_dialog->set_size(Size2(225, 270) * EDSCALE);
9373 layout_dialog->connect("name_confirmed", callable_mp(this, &EditorNode::_dialog_action));
9374
9375 update_spinner = memnew(MenuButton);
9376 right_menu_hb->add_child(update_spinner);
9377 update_spinner->set_button_icon(theme->get_icon(SNAME("Progress1"), EditorStringName(EditorIcons)));
9378 update_spinner->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
9379 update_spinner->set_accessibility_name(TTRC("Update Mode"));
9380 PopupMenu *p = update_spinner->get_popup();
9381 p->add_radio_check_item(TTRC("Update Continuously"), SPINNER_UPDATE_CONTINUOUSLY);
9382 p->add_radio_check_item(TTRC("Update When Changed"), SPINNER_UPDATE_WHEN_CHANGED);
9383 p->add_separator();
9384 p->add_item(TTRC("Hide Update Spinner"), SPINNER_UPDATE_SPINNER_HIDE);
9385 _update_update_spinner();
9386
9387 // Instantiate and place editor docks.
9388
9389 memnew(SceneTreeDock(scene_root, editor_selection, editor_data));
9390 editor_dock_manager->add_dock(SceneTreeDock::get_singleton());
9391
9392 memnew(ImportDock);
9393 editor_dock_manager->add_dock(ImportDock::get_singleton());
9394
9395 FileSystemDock *filesystem_dock = memnew(FileSystemDock);
9396 filesystem_dock->connect("inherit", callable_mp(this, &EditorNode::_inherit_request));
9397 filesystem_dock->connect("instantiate", callable_mp(this, &EditorNode::_instantiate_request));
9398 filesystem_dock->connect("display_mode_changed", callable_mp(this, &EditorNode::_save_editor_layout));
9399 get_project_settings()->connect_filesystem_dock_signals(filesystem_dock);
9400 editor_dock_manager->add_dock(filesystem_dock);
9401
9402 memnew(InspectorDock(editor_data));
9403 editor_dock_manager->add_dock(InspectorDock::get_singleton());
9404
9405 memnew(SignalsDock);
9406 editor_dock_manager->add_dock(SignalsDock::get_singleton());
9407
9408 memnew(GroupsDock);
9409 editor_dock_manager->add_dock(GroupsDock::get_singleton());
9410
9411 history_dock = memnew(HistoryDock);
9412 editor_dock_manager->add_dock(history_dock);
9413
9414 // Add some offsets to make LEFT_R and RIGHT_L docks wider than minsize.
9415 const int dock_hsize = 280;
9416 // By default there is only 3 visible, so set 2 split offsets for them.
9417 const int dock_hsize_scaled = dock_hsize * EDSCALE;
9418 main_hsplit->set_split_offsets({ dock_hsize_scaled, -dock_hsize_scaled });
9419
9420 // Bottom panels.
9421
9422 bottom_panel = memnew(EditorBottomPanel);
9423 editor_dock_manager->register_dock_slot(bottom_panel);
9424 center_split->add_child(bottom_panel);
9425 center_split->set_dragger_visibility(SplitContainer::DRAGGER_HIDDEN);
9426
9427 log = memnew(EditorLog);
9428 editor_dock_manager->add_dock(log);
9429
9430 center_split->connect(SceneStringName(resized), callable_mp(this, &EditorNode::_vp_resized));
9431
9432 native_shader_source_visualizer = memnew(EditorNativeShaderSourceVisualizer);
9433 gui_base->add_child(native_shader_source_visualizer);
9434
9435 orphan_resources = memnew(OrphanResourcesDialog);
9436 gui_base->add_child(orphan_resources);
9437
9438 confirmation = memnew(ConfirmationDialog);
9439 confirmation_button = confirmation->add_button(TTRC("Don't Save"), DisplayServer::get_singleton()->get_swap_cancel_ok(), "discard");
9440 gui_base->add_child(confirmation);
9441 confirmation->set_min_size(Vector2(450.0 * EDSCALE, 0));
9442 confirmation->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
9443 confirmation->connect("custom_action", callable_mp(this, &EditorNode::_discard_changes));
9444 confirmation->connect("canceled", callable_mp(this, &EditorNode::_cancel_confirmation));
9445
9446 save_confirmation = memnew(ConfirmationDialog);
9447 save_confirmation->add_button(TTRC("Don't Save"), DisplayServer::get_singleton()->get_swap_cancel_ok(), "discard");
9448 gui_base->add_child(save_confirmation);
9449 save_confirmation->set_min_size(Vector2(450.0 * EDSCALE, 0));
9450 save_confirmation->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
9451 save_confirmation->connect("custom_action", callable_mp(this, &EditorNode::_discard_changes));
9452 save_confirmation->connect("canceled", callable_mp(this, &EditorNode::_cancel_close_scene_tab));
9453 save_confirmation->connect("about_to_popup", callable_mp(this, &EditorNode::_prepare_save_confirmation_popup));
9454
9455 gradle_build_manage_templates = memnew(ConfirmationDialog);
9456 gradle_build_manage_templates->set_flag(Window::FLAG_RESIZE_DISABLED, true);
9457 gradle_build_manage_templates->set_text(TTR("Android build template is missing, please install relevant templates."));
9458 gradle_build_manage_templates->set_ok_button_text(TTR("Manage Templates"));
9459 gradle_build_manage_templates->add_button(TTR("Install from file"))->connect(SceneStringName(pressed), callable_mp(this, &EditorNode::_android_install_build_template));
9460 gradle_build_manage_templates->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(EDITOR_MANAGE_EXPORT_TEMPLATES));
9461 gui_base->add_child(gradle_build_manage_templates);
9462
9463 file_android_build_source = memnew(EditorFileDialog);
9464 file_android_build_source->set_title(TTR("Select Android sources file"));
9465 file_android_build_source->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
9466 file_android_build_source->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
9467 file_android_build_source->add_filter("*.zip");
9468 file_android_build_source->connect("file_selected", callable_mp(this, &EditorNode::_android_build_source_selected));
9469 gui_base->add_child(file_android_build_source);
9470
9471 {
9472 VBoxContainer *vbox = memnew(VBoxContainer);
9473 install_android_build_template_message = memnew(Label);
9474 install_android_build_template_message->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
9475 install_android_build_template_message->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
9476 install_android_build_template_message->set_custom_minimum_size(Size2(300 * EDSCALE, 1));
9477 vbox->add_child(install_android_build_template_message);
9478
9479 choose_android_export_profile = memnew(OptionButton);
9480 choose_android_export_profile->connect(SceneStringName(item_selected), callable_mp(this, &EditorNode::_android_export_preset_selected));
9481 vbox->add_child(choose_android_export_profile);
9482
9483 install_android_build_template = memnew(ConfirmationDialog);
9484 install_android_build_template->set_flag(Window::FLAG_RESIZE_DISABLED, true);
9485 install_android_build_template->set_ok_button_text(TTR("Install"));
9486 install_android_build_template->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
9487 install_android_build_template->add_child(vbox);
9488 install_android_build_template->set_min_size(Vector2(500.0 * EDSCALE, 0));
9489 gui_base->add_child(install_android_build_template);
9490 }
9491
9492 remove_android_build_template = memnew(ConfirmationDialog);
9493 remove_android_build_template->set_ok_button_text(OS::get_singleton()->get_platform_string(OS::PLATFORM_STRING_FILE_MANAGER_OPEN));
9494 remove_android_build_template->set_autowrap(true);
9495 remove_android_build_template->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_android_explore_build_templates));
9496 gui_base->add_child(remove_android_build_template);
9497
9498 file_templates = memnew(EditorFileDialog);
9499 file_templates->set_title(TTR("Import Templates From ZIP File"));
9500
9501 gui_base->add_child(file_templates);
9502 file_templates->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
9503 file_templates->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
9504 file_templates->clear_filters();
9505 file_templates->add_filter("*.tpz", TTR("Template Package"));
9506
9507 file = memnew(EditorFileDialog);
9508 gui_base->add_child(file);
9509 file->set_current_dir("res://");
9510 file->set_transient_to_focused(true);
9511
9512 file_export_lib = memnew(EditorFileDialog);
9513 file_export_lib->set_title(TTR("Export Library"));
9514 file_export_lib->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
9515 file_export_lib->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
9516 file_export_lib->add_option(TTR("Merge With Existing"), Vector<String>(), true);
9517 file_export_lib->add_option(TTR("Apply MeshInstance Transforms"), Vector<String>(), false);
9518 gui_base->add_child(file_export_lib);
9519
9520 file_pack_zip = memnew(EditorFileDialog);
9521 file_pack_zip->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
9522 file_pack_zip->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
9523 file_pack_zip->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
9524 file_pack_zip->add_filter("*.zip", "ZIP Archive");
9525 file_pack_zip->set_title(TTR("Pack Project as ZIP..."));
9526 gui_base->add_child(file_pack_zip);
9527
9528 file->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
9529 file_templates->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
9530
9531 audio_preview_gen = memnew(AudioStreamPreviewGenerator);
9532 add_child(audio_preview_gen);
9533
9534 add_editor_plugin(memnew(DebuggerEditorPlugin(debug_menu)));
9535
9536 disk_changed = memnew(ConfirmationDialog);
9537 {
9538 disk_changed->set_title(TTR("Files have been modified outside Godot"));
9539
9540 VBoxContainer *vbc = memnew(VBoxContainer);
9541 disk_changed->add_child(vbc);
9542
9543 Label *dl = memnew(Label);
9544 dl->set_text(TTR("The following files are newer on disk:"));
9545 vbc->add_child(dl);
9546
9547 disk_changed_list = memnew(Tree);
9548 disk_changed_list->set_accessibility_name(TTRC("The following files are newer on disk:"));
9549 vbc->add_child(disk_changed_list);
9550 disk_changed_list->set_v_size_flags(Control::SIZE_EXPAND_FILL);
9551
9552 Label *what_action_label = memnew(Label);
9553 what_action_label->set_text(TTR("What action should be taken?"));
9554 vbc->add_child(what_action_label);
9555
9556 disk_changed->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_reload_modified_scenes));
9557 disk_changed->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_reload_project_settings));
9558 disk_changed->set_ok_button_text(TTR("Reload from disk"));
9559
9560 disk_changed->add_button(TTR("Ignore external changes"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "resave");
9561 disk_changed->connect("custom_action", callable_mp(this, &EditorNode::_resave_externally_modified_scenes));
9562 }
9563
9564 gui_base->add_child(disk_changed);
9565
9566 project_data_missing = memnew(ConfirmationDialog);
9567 project_data_missing->set_flag(Window::FLAG_RESIZE_DISABLED, true);
9568 project_data_missing->set_text(TTRC("Project data folder (.godot) is missing. Please restart editor."));
9569 project_data_missing->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::restart_editor).bind(false));
9570 project_data_missing->set_ok_button_text(TTRC("Restart"));
9571
9572 gui_base->add_child(project_data_missing);
9573
9574 add_editor_plugin(memnew(CanvasItemEditorPlugin));
9575 add_editor_plugin(memnew(Node3DEditorPlugin));
9576 add_editor_plugin(memnew(ScriptEditorPlugin));
9577
9578 if (!Engine::get_singleton()->is_recovery_mode_hint()) {
9579 add_editor_plugin(get_game_view_plugin());
9580 }
9581
9582 EditorAudioBuses *audio_bus_editor = EditorAudioBuses::register_editor();
9583
9584 ScriptTextEditor::register_editor(); // Register one for text scripts.
9585 TextEditor::register_editor();
9586 ShaderTextEditor::register_editor();
9587
9588 if (AssetLibraryEditorPlugin::is_available()) {
9589 add_editor_plugin(memnew(AssetLibraryEditorPlugin));
9590 } else {
9591 print_verbose("Asset Store not available (due to using Web editor, or SSL support disabled).");
9592 }
9593
9594 // More visually meaningful to have this later.
9595 add_editor_plugin(memnew(AnimationPlayerEditorPlugin));
9596 add_editor_plugin(memnew(AnimationTrackKeyEditEditorPlugin));
9597 add_editor_plugin(memnew(AnimationMarkerKeyEditEditorPlugin));
9598
9599 add_editor_plugin(VersionControlEditorPlugin::get_singleton());
9600
9601 add_editor_plugin(memnew(AudioBusesEditorPlugin(audio_bus_editor)));
9602
9603 for (int i = 0; i < EditorPlugins::get_plugin_count(); i++) {
9604 add_editor_plugin(EditorPlugins::create(i));
9605 }
9606
9607 for (const StringName &extension_class_name : GDExtensionEditorPlugins::get_extension_classes()) {
9608 add_extension_editor_plugin(extension_class_name);
9609 }
9610 GDExtensionEditorPlugins::editor_node_add_plugin = &EditorNode::add_extension_editor_plugin;
9611 GDExtensionEditorPlugins::editor_node_remove_plugin = &EditorNode::remove_extension_editor_plugin;
9612
9613 for (int i = 0; i < plugin_init_callback_count; i++) {
9614 plugin_init_callbacks[i]();
9615 }
9616
9617 resource_preview->add_preview_generator(Ref<EditorTexturePreviewPlugin>(memnew(EditorTexturePreviewPlugin)));
9618 resource_preview->add_preview_generator(Ref<EditorImagePreviewPlugin>(memnew(EditorImagePreviewPlugin)));
9619 resource_preview->add_preview_generator(Ref<EditorPackedScenePreviewPlugin>(memnew(EditorPackedScenePreviewPlugin)));
9620 resource_preview->add_preview_generator(Ref<EditorMaterialPreviewPlugin>(memnew(EditorMaterialPreviewPlugin)));
9621 resource_preview->add_preview_generator(Ref<EditorScriptPreviewPlugin>(memnew(EditorScriptPreviewPlugin)));
9622 resource_preview->add_preview_generator(Ref<EditorAudioStreamPreviewPlugin>(memnew(EditorAudioStreamPreviewPlugin)));
9623 resource_preview->add_preview_generator(Ref<EditorMeshPreviewPlugin>(memnew(EditorMeshPreviewPlugin)));
9624 resource_preview->add_preview_generator(Ref<EditorBitmapPreviewPlugin>(memnew(EditorBitmapPreviewPlugin)));
9625 resource_preview->add_preview_generator(Ref<EditorFontPreviewPlugin>(memnew(EditorFontPreviewPlugin)));
9626 resource_preview->add_preview_generator(Ref<EditorGradientPreviewPlugin>(memnew(EditorGradientPreviewPlugin)));
9627
9628 {
9629 Ref<CanvasItemMaterialConversionPlugin> canvas_item_mat_convert;
9630 canvas_item_mat_convert.instantiate();
9631 resource_conversion_plugins.push_back(canvas_item_mat_convert);
9632
9633 Ref<BlitMaterialConversionPlugin> blit_mat_convert;
9634 blit_mat_convert.instantiate();
9635 resource_conversion_plugins.push_back(blit_mat_convert);
9636
9637 Ref<ParticleProcessMaterialConversionPlugin> particles_mat_convert;
9638 particles_mat_convert.instantiate();
9639 resource_conversion_plugins.push_back(particles_mat_convert);
9640
9641 Ref<StandardMaterial3DConversionPlugin> spatial_mat_convert;
9642 spatial_mat_convert.instantiate();
9643 resource_conversion_plugins.push_back(spatial_mat_convert);
9644
9645 Ref<ORMMaterial3DConversionPlugin> orm_mat_convert;
9646 orm_mat_convert.instantiate();
9647 resource_conversion_plugins.push_back(orm_mat_convert);
9648
9649 Ref<ProceduralSkyMaterialConversionPlugin> procedural_sky_mat_convert;
9650 procedural_sky_mat_convert.instantiate();
9651 resource_conversion_plugins.push_back(procedural_sky_mat_convert);
9652
9653 Ref<PanoramaSkyMaterialConversionPlugin> panorama_sky_mat_convert;
9654 panorama_sky_mat_convert.instantiate();
9655 resource_conversion_plugins.push_back(panorama_sky_mat_convert);
9656
9657 Ref<PhysicalSkyMaterialConversionPlugin> physical_sky_mat_convert;
9658 physical_sky_mat_convert.instantiate();
9659 resource_conversion_plugins.push_back(physical_sky_mat_convert);
9660
9661 Ref<FogMaterialConversionPlugin> fog_mat_convert;
9662 fog_mat_convert.instantiate();
9663 resource_conversion_plugins.push_back(fog_mat_convert);
9664 }
9665
9666 update_spinner_step_msec = OS::get_singleton()->get_ticks_msec();
9667 update_spinner_step_frame = Engine::get_singleton()->get_frames_drawn();
9668
9669 editor_plugins_over = memnew(EditorPluginList);
9670 editor_plugins_force_over = memnew(EditorPluginList);
9671 editor_plugins_force_input_forwarding = memnew(EditorPluginList);
9672
9673 Ref<GDExtensionExportPlugin> gdextension_export_plugin;
9674 gdextension_export_plugin.instantiate();
9675
9676 EditorExport::get_singleton()->add_export_plugin(gdextension_export_plugin);
9677
9678 Ref<DedicatedServerExportPlugin> dedicated_server_export_plugin;
9679 dedicated_server_export_plugin.instantiate();
9680
9681 EditorExport::get_singleton()->add_export_plugin(dedicated_server_export_plugin);
9682
9683#ifdef RD_ENABLED
9684 Ref<ShaderBakerExportPlugin> shader_baker_export_plugin;
9685 shader_baker_export_plugin.instantiate();
9686
9687#ifdef VULKAN_ENABLED
9688 Ref<ShaderBakerExportPluginPlatformVulkan> shader_baker_export_plugin_platform_vulkan;
9689 shader_baker_export_plugin_platform_vulkan.instantiate();
9690 shader_baker_export_plugin->add_platform(shader_baker_export_plugin_platform_vulkan);
9691#endif
9692
9693#ifdef D3D12_ENABLED
9694 Ref<ShaderBakerExportPluginPlatformD3D12> shader_baker_export_plugin_platform_d3d12;
9695 shader_baker_export_plugin_platform_d3d12.instantiate();
9696 shader_baker_export_plugin->add_platform(shader_baker_export_plugin_platform_d3d12);
9697#endif
9698
9699#ifdef METAL_ENABLED
9700 Ref<ShaderBakerExportPluginPlatformMetal> shader_baker_export_plugin_platform_metal;
9701 shader_baker_export_plugin_platform_metal.instantiate();
9702 shader_baker_export_plugin->add_platform(shader_baker_export_plugin_platform_metal);
9703#endif
9704
9705 EditorExport::get_singleton()->add_export_plugin(shader_baker_export_plugin);
9706#endif // RD_ENABLED
9707
9708 Ref<PackedSceneEditorTranslationParserPlugin> packed_scene_translation_parser_plugin;
9709 packed_scene_translation_parser_plugin.instantiate();
9710 EditorTranslationParser::get_singleton()->add_parser(packed_scene_translation_parser_plugin, EditorTranslationParser::STANDARD);
9711
9712 _edit_current();
9713 saving_resource = Ref<Resource>();
9714
9715 set_process(true);
9716
9717 open_imported = memnew(ConfirmationDialog);
9718 open_imported->set_flag(Window::FLAG_RESIZE_DISABLED, true);
9719 open_imported->set_ok_button_text(TTR("Open Anyway"));
9720 new_inherited_button = open_imported->add_button(TTR("New Inherited"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "inherit");
9721 open_imported->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_open_imported));
9722 open_imported->connect("custom_action", callable_mp(this, &EditorNode::_inherit_imported));
9723 gui_base->add_child(open_imported);
9724
9725 quick_open_dialog = memnew(EditorQuickOpenDialog);
9726 gui_base->add_child(quick_open_dialog);
9727
9728 quick_open_color_palette = memnew(EditorQuickOpenDialog);
9729 gui_base->add_child(quick_open_color_palette);
9730
9731 _update_recent_scenes();
9732
9733 set_process_shortcut_input(true);
9734
9735 load_errors = memnew(RichTextLabel);
9736 load_error_dialog = memnew(AcceptDialog);
9737 load_error_dialog->set_unparent_when_invisible(true);
9738 load_error_dialog->add_child(load_errors);
9739 load_error_dialog->set_title(TTR("Load Errors"));
9740 load_error_dialog->connect(SceneStringName(visibility_changed), callable_mp(this, &EditorNode::_load_error_dialog_visibility_changed));
9741
9742 execute_outputs = memnew(RichTextLabel);
9743 execute_outputs->set_selection_enabled(true);
9744 execute_outputs->set_context_menu_enabled(true);
9745 execute_output_dialog = memnew(AcceptDialog);
9746 execute_output_dialog->set_unparent_when_invisible(true);
9747 execute_output_dialog->add_child(execute_outputs);
9748 execute_output_dialog->set_title("");
9749
9750 EditorFileSystem::get_singleton()->connect("sources_changed", callable_mp(this, &EditorNode::_sources_changed));
9751 EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &EditorNode::_fs_changed));
9752 EditorFileSystem::get_singleton()->connect("resources_reimporting", callable_mp(this, &EditorNode::_resources_reimporting));
9753 EditorFileSystem::get_singleton()->connect("resources_reimported", callable_mp(this, &EditorNode::_resources_reimported));
9754 EditorFileSystem::get_singleton()->connect("resources_reload", callable_mp(this, &EditorNode::_resources_changed));
9755
9756 _build_icon_type_cache();
9757
9758 pick_main_scene = memnew(ConfirmationDialog);
9759 gui_base->add_child(pick_main_scene);
9760 pick_main_scene->set_ok_button_text(TTR("Select"));
9761 pick_main_scene->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(SETTINGS_PICK_MAIN_SCENE));
9762 select_current_scene_button = pick_main_scene->add_button(TTR("Select Current"), true, "select_current");
9763 pick_main_scene->connect("custom_action", callable_mp(this, &EditorNode::_pick_main_scene_custom_action));
9764
9765 open_project_settings = memnew(ConfirmationDialog);
9766 gui_base->add_child(open_project_settings);
9767 open_project_settings->set_ok_button_text(TTRC("Open Project Settings"));
9768 open_project_settings->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(PROJECT_OPEN_SETTINGS));
9769
9770 for (int i = 0; i < _init_callbacks.size(); i++) {
9771 _init_callbacks[i]();
9772 }
9773
9774 editor_data.add_edited_scene(-1);
9775 editor_data.set_edited_scene(0);
9776 scene_tabs->update_scene_tabs();
9777
9778 ImportDock::get_singleton()->initialize_import_options();
9779
9780 FileAccess::set_file_close_fail_notify_callback(_file_access_close_error_notify);
9781
9782 print_handler.printfunc = _print_handler;
9783 print_handler.userdata = this;
9784 add_print_handler(&print_handler);
9785
9786 ResourceSaver::set_save_callback(_resource_saved);
9787 ResourceLoader::set_load_callback(_resource_loaded);
9788
9789 // Apply setting presets in case the editor_settings file is missing values.
9790 EditorSettingsDialog::update_3d_navigation_preset();
9791
9792 screenshot_timer = memnew(Timer);
9793 screenshot_timer->set_one_shot(true);
9794 screenshot_timer->set_wait_time(settings_menu->get_submenu_popup_delay() + 0.1f);
9795 screenshot_timer->connect("timeout", callable_mp(this, &EditorNode::_request_screenshot));
9796 add_child(screenshot_timer);
9797 screenshot_timer->set_owner(get_owner());
9798
9799 // Extend menu bar to window title.
9800 if (can_expand) {
9801 DisplayServer::get_singleton()->process_events();
9802 DisplayServer::get_singleton()->window_set_flag(DisplayServerEnums::WINDOW_FLAG_EXTEND_TO_TITLE, true, DisplayServerEnums::MAIN_WINDOW_ID);
9803 title_bar->set_can_move_window(true);
9804 }
9805
9806 {
9807 const String exec = OS::get_singleton()->get_executable_path();
9808 const String old_exec = EditorSettings::get_singleton()->get_project_metadata("editor_metadata", "executable_path", "");
9809 // Save editor executable path for third-party tools.
9810 if (exec != old_exec) {
9811 EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "executable_path", exec);
9812 }
9813 }
9814
9815 follow_system_theme = EDITOR_GET("interface/theme/follow_system_theme");
9816 use_system_accent_color = EDITOR_GET("interface/theme/use_system_accent_color");
9817
9818 // Define the default layout after everything is initialized.
9819
9820 default_layout.instantiate();
9821 const String docks_section = "docks";
9822 {
9823 const String scene_key = SceneTreeDock::get_singleton()->get_effective_layout_key();
9824 const String import_key = ImportDock::get_singleton()->get_effective_layout_key();
9825 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_LEFT_UR), vformat("%s,%s", scene_key, import_key));
9826 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_LEFT_UR) + "_selected_tab_idx", 0);
9827 }
9828 {
9829 const String filesystem_key = filesystem_dock->get_effective_layout_key();
9830 const String history_key = history_dock->get_effective_layout_key();
9831 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_LEFT_BR), vformat("%s,%s", filesystem_key, history_key));
9832 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_LEFT_BR) + "_selected_tab_idx", 0);
9833 }
9834 {
9835 const String inspector_key = InspectorDock::get_singleton()->get_effective_layout_key();
9836 const String signals_key = SignalsDock::get_singleton()->get_effective_layout_key();
9837 const String groups_key = GroupsDock::get_singleton()->get_effective_layout_key();
9838 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_RIGHT_UL), vformat("%s,%s,%s", inspector_key, signals_key, groups_key));
9839 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_RIGHT_UL) + "_selected_tab_idx", 0);
9840 }
9841 {
9842 const String _2d_key = CanvasItemEditor::get_singleton()->get_effective_layout_key();
9843 const String _3d_key = Node3DEditor::get_singleton()->get_effective_layout_key();
9844 const String script_key = ScriptEditor::get_singleton()->get_effective_layout_key();
9845 String game_key;
9846 if (GameView::get_dock()) {
9847 game_key = GameView::get_dock()->get_effective_layout_key();
9848 }
9849 String asset_lib_key;
9850 if (AssetLibraryEditorPlugin::get_library()) {
9851 asset_lib_key = AssetLibraryEditorPlugin::get_library()->get_effective_layout_key();
9852 }
9853 default_layout->set_value(docks_section, DockTabContainer::get_config_key(EditorDock::DOCK_SLOT_MAIN_SCREEN), vformat("%s,%s,%s,%s,%s", _2d_key, _3d_key, script_key, game_key, asset_lib_key));
9854 }
9855
9856 int hsplits[] = { 0, dock_hsize, -dock_hsize, 0 };
9857 for (int i = 0; i < (int)std_size(hsplits); i++) {
9858 default_layout->set_value(docks_section, "dock_hsplit_" + itos(i + 1), hsplits[i]);
9859 }
9860 for (int i = 0; i < editor_dock_manager->get_vsplit_count(); i++) {
9861 default_layout->set_value(docks_section, "dock_split_" + itos(i + 1), 0);
9862 }
9863
9864 {
9865 const String output_key = log->get_effective_layout_key();
9866 const String audio_key = audio_bus_editor->get_effective_layout_key();
9867 const String shader_key = ShaderEditorPlugin::get_singleton()->get_shader_dock()->get_effective_layout_key();
9868
9869 Dictionary offsets;
9870 offsets[output_key] = -270;
9871 offsets[audio_key] = -450;
9872 offsets[shader_key] = -348;
9873 default_layout->set_value(EDITOR_NODE_CONFIG_SECTION, "bottom_panel_offsets", offsets);
9874 }
9875
9876 _update_layouts_menu();
9877}
9878
9879EditorNode::~EditorNode() {
9880 EditorInspector::cleanup_plugins();
9881 EditorTranslationParser::get_singleton()->clean_parsers();
9882 ResourceImporterScene::clean_up_importer_plugins();
9883 EditorContextMenuPluginManager::cleanup();
9884
9885 remove_print_handler(&print_handler);
9886 EditorHelp::cleanup_doc();
9887#if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
9888 EditorHelpHighlighter::free_singleton();
9889#endif
9890 memdelete(editor_selection);
9891 memdelete(editor_plugins_over);
9892 memdelete(editor_plugins_force_over);
9893 memdelete(editor_plugins_force_input_forwarding);
9894 memdelete(progress_hb);
9895 memdelete(project_upgrade_tool);
9896 memdelete(editor_dock_manager);
9897
9898 EditorSettings::destroy();
9899 EditorThemeManager::finalize();
9900
9901 GDExtensionEditorPlugins::editor_node_add_plugin = nullptr;
9902 GDExtensionEditorPlugins::editor_node_remove_plugin = nullptr;
9903
9904 FileDialog::register_func = nullptr;
9905 FileDialog::unregister_func = nullptr;
9906
9907 file_dialogs.clear();
9908
9909 singleton = nullptr;
9910}