Debian Codegraph @

editor/editor_node.cpp

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