/*************************************************************************/ /* script_editor_debugger.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "script_editor_debugger.h" #include "core/error/error_list.h" #include "core/error/error_macros.h" #include "core/io/marshalls.h" #include "core/io/multiplayer_api.h" #include "core/io/packet_peer.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/stream_peer.h" #include "core/io/stream_peer_tcp.h" #include "core/io/tcp_server.h" #include "core/math/color.h" #include "core/math/math_defs.h" #include "core/math/math_funcs.h" #include "core/math/rect2.h" #include "core/math/transform_2d.h" #include "core/object/class_db.h" #include "core/object/ref_ptr.h" #include "core/object/script_language.h" #include "core/object/undo_redo.h" #include "core/os/file_access.h" #include "core/os/memory.h" #include "core/os/os.h" #include "core/string/print_string.h" #include "core/string/ustring.h" #include "core/typedefs.h" #include "core/variant/dictionary.h" #include "core/version.h" #include "editor/editor_data.h" #include "editor/editor_file_dialog.h" #include "editor/editor_inspector.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor/plugins/spatial_editor_plugin.h" #include "editor/scene_tree_dock.h" #include "editor_log.h" #include "editor_network_profiler.h" #include "editor_node.h" #include "editor_profiler.h" #include "editor_scale.h" #include "editor_settings.h" #include "main/performance.h" #include "scene/3d/camera.h" #include "scene/debugger/script_debugger_remote.h" #include "scene/gui/box_container.h" #include "scene/gui/button.h" #include "scene/main/control.h" #include "scene/gui/dialogs.h" #include "scene/gui/grid_container.h" #include "scene/gui/label.h" #include "scene/gui/line_edit.h" #include "scene/gui/margin_container.h" #include "scene/gui/option_button.h" #include "scene/gui/popup_menu.h" #include "scene/gui/separator.h" #include "scene/gui/split_container.h" #include "scene/gui/tab_container.h" #include "scene/gui/tool_button.h" #include "scene/gui/tree.h" #include "scene/main/node.h" #include "scene/resources/font/font.h" #include "scene/resources/packed_scene.h" #include "scene/resources/style_box.h" #include "scene/resources/texture.h" class EditorScriptEditorDebuggerVariables : public Object { GDCLASS(EditorScriptEditorDebuggerVariables, Object); List props; RBMap values; protected: bool _set(const StringName &p_name, const Variant &p_value) { return false; } bool _get(const StringName &p_name, Variant &r_ret) const { if (!values.has(p_name)) { return false; } r_ret = values[p_name]; return true; } void _get_property_list(List *p_list) const { for (const List::Element *E = props.front(); E; E = E->next()) { p_list->push_back(E->get()); } } public: void clear() { props.clear(); values.clear(); } String get_var_value(const String &p_var) const { for (RBMap::Element *E = values.front(); E; E = E->next()) { String v = E->key().operator String().get_slice("/", 1); if (v == p_var) { return E->get(); } } return ""; } void add_property(const String &p_name, const Variant &p_value, const PropertyHint &p_hint, const String p_hint_string) { PropertyInfo pinfo; pinfo.name = p_name; pinfo.type = p_value.get_type(); pinfo.hint = p_hint; pinfo.hint_string = p_hint_string; props.push_back(pinfo); values[p_name] = p_value; } void update() { _change_notify(); } EditorScriptEditorDebuggerVariables() { } }; class EditorScriptEditorDebuggerInspectedObject : public Object { GDCLASS(EditorScriptEditorDebuggerInspectedObject, Object); protected: bool _set(const StringName &p_name, const Variant &p_value) { if (!prop_values.has(p_name) || String(p_name).begins_with("Constants/")) { return false; } prop_values[p_name] = p_value; emit_signal("value_edited", p_name, p_value); return true; } bool _get(const StringName &p_name, Variant &r_ret) const { if (!prop_values.has(p_name)) { return false; } r_ret = prop_values[p_name]; return true; } void _get_property_list(List *p_list) const { p_list->clear(); // Sorry, no want category. for (const List::Element *E = prop_list.front(); E; E = E->next()) { const PropertyInfo &prop = E->get(); if (prop.name == "script") { // Skip the script property, it's always added by the non-virtual method. continue; } p_list->push_back(prop); } } static void _bind_methods() { ClassDB::bind_method(D_METHOD("get_title"), &EditorScriptEditorDebuggerInspectedObject::get_title); ClassDB::bind_method(D_METHOD("get_variant"), &EditorScriptEditorDebuggerInspectedObject::get_variant); ClassDB::bind_method(D_METHOD("clear"), &EditorScriptEditorDebuggerInspectedObject::clear); ClassDB::bind_method(D_METHOD("get_remote_object_id"), &EditorScriptEditorDebuggerInspectedObject::get_remote_object_id); ADD_SIGNAL(MethodInfo("value_edited")); } public: String type_name; ObjectID remote_object_id; List prop_list; RBMap prop_values; ObjectID get_remote_object_id() { return remote_object_id; } String get_title() { if (remote_object_id) { return TTR("Remote ") + String(type_name) + ": " + itos(remote_object_id); } else { return ""; } } Variant get_variant(const StringName &p_name) { Variant var; _get(p_name, var); return var; } void clear() { prop_list.clear(); prop_values.clear(); } void update() { _change_notify(); } void update_single(const char *p_prop) { _change_notify(p_prop); } EditorScriptEditorDebuggerInspectedObject() { remote_object_id = 0; } }; void EditorScriptEditorDebugger::debug_copy() { String msg = reason->get_text(); if (msg == "") { return; } OS::get_singleton()->set_clipboard(msg); } void EditorScriptEditorDebugger::debug_skip_breakpoints() { skip_breakpoints_value = !skip_breakpoints_value; if (skip_breakpoints_value) { skip_breakpoints->set_icon(get_theme_icon("DebugSkipBreakpointsOn", "EditorIcons")); } else { skip_breakpoints->set_icon(get_theme_icon("DebugSkipBreakpointsOff", "EditorIcons")); } if (connection.is_valid()) { Array msg; msg.push_back("set_skip_breakpoints"); msg.push_back(debugging_thread_id != 0 ? debugging_thread_id : process_main_thread_id); msg.push_back(skip_breakpoints_value); ppeer->put_var(msg); } } void EditorScriptEditorDebugger::debug_next() { ERR_FAIL_COND(!is_breaked()); ERR_FAIL_COND(connection.is_null()); ERR_FAIL_COND(!connection->is_connected_to_host()); Array msg; msg.push_back("next"); msg.push_back(debugging_thread_id); ppeer->put_var(msg); _clear_execution(); } void EditorScriptEditorDebugger::debug_step() { ERR_FAIL_COND(!is_breaked()); ERR_FAIL_COND(connection.is_null()); ERR_FAIL_COND(!connection->is_connected_to_host()); Array msg; msg.push_back("step"); msg.push_back(debugging_thread_id); ppeer->put_var(msg); _clear_execution(); } void EditorScriptEditorDebugger::debug_break() { ERR_FAIL_COND(is_breaked()); ERR_FAIL_COND(connection.is_null()); ERR_FAIL_COND(!connection->is_connected_to_host()); Array msg; msg.push_back("break"); msg.push_back(process_main_thread_id); ppeer->put_var(msg); } void EditorScriptEditorDebugger::debug_continue() { ERR_FAIL_COND(!is_breaked()); ERR_FAIL_COND(connection.is_null()); ERR_FAIL_COND(!connection->is_connected_to_host()); OS::get_singleton()->enable_for_stealing_focus(EditorNode::get_singleton()->get_child_process_id()); Array msg; _clear_execution(); msg.push_back("continue"); msg.push_back(debugging_thread_id); ppeer->put_var(msg); } bool EditorScriptEditorDebugger::is_session_active() { return !connection.is_null() && connection->is_connected_to_host(); } void EditorScriptEditorDebugger::_scene_tree_folded(Object *obj) { if (updating_scene_tree) { return; } TreeItem *item = Object::cast_to(obj); if (!item) { return; } ObjectID id = item->get_metadata(0); if (unfold_cache.has(id)) { unfold_cache.erase(id); } else { unfold_cache.insert(id); } } void EditorScriptEditorDebugger::_scene_tree_selected() { if (updating_scene_tree) { return; } TreeItem *item = inspect_scene_tree->get_selected(); if (!item) { return; } inspected_object_id = item->get_metadata(0); Array msg; msg.push_back("inspect_object"); msg.push_back(process_main_thread_id); msg.push_back(inspected_object_id); ppeer->put_var(msg); } void EditorScriptEditorDebugger::_scene_tree_rmb_selected(const Vector2 &p_position) { TreeItem *item = inspect_scene_tree->get_item_at_position(p_position); if (!item) { return; } item->select(0); item_menu->clear(); item_menu->add_icon_item(get_theme_icon("CreateNewSceneFrom", "EditorIcons"), TTR("Save Branch as Scene"), ITEM_MENU_SAVE_REMOTE_NODE); item_menu->add_icon_item(get_theme_icon("CopyNodePath", "EditorIcons"), TTR("Copy Node Path"), ITEM_MENU_COPY_NODE_PATH); item_menu->set_global_position(get_global_mouse_position()); item_menu->popup(); } void EditorScriptEditorDebugger::_file_selected(const String &p_file) { switch (file_dialog_mode) { case SAVE_NODE: { Array msg; msg.push_back("save_node"); msg.push_back(process_main_thread_id); msg.push_back(inspected_object_id); msg.push_back(p_file); ppeer->put_var(msg); } break; case SAVE_MONITORS_CSV: { Error err; FileAccessRef file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open " + p_file); return; } Vector line; line.resize(Performance::MONITOR_MAX); // signatures for (int i = 0; i < Performance::MONITOR_MAX; i++) { line.write[i] = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)); } file->store_csv_line(line); // values List>::Element *E = perf_history.back(); while (E) { Vector &perf_data = E->get(); for (int i = 0; i < perf_data.size(); i++) { line.write[i] = String::num_real(perf_data[i]); } file->store_csv_line(line); E = E->prev(); } file->store_string("\n"); Vector> profiler_data = profiler->get_data_as_csv(); for (int i = 0; i < profiler_data.size(); i++) { file->store_csv_line(profiler_data[i]); } } break; case SAVE_VRAM_CSV: { Error err; FileAccessRef file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open " + p_file); return; } Vector headers; headers.resize(vmem_tree->get_columns()); for (int i = 0; i < vmem_tree->get_columns(); ++i) { headers.write[i] = vmem_tree->get_column_title(i); } file->store_csv_line(headers); if (vmem_tree->get_root()) { TreeItem *ti = vmem_tree->get_root()->get_children(); while (ti) { Vector values; values.resize(vmem_tree->get_columns()); for (int i = 0; i < vmem_tree->get_columns(); ++i) { values.write[i] = ti->get_text(i); } file->store_csv_line(values); ti = ti->get_next(); } } } break; } } void EditorScriptEditorDebugger::_scene_tree_property_value_edited(const String &p_prop, const Variant &p_value) { Array msg; msg.push_back("set_object_property"); msg.push_back(process_main_thread_id); msg.push_back(inspected_object_id); msg.push_back(p_prop); msg.push_back(p_value); ppeer->put_var(msg); inspect_edited_object_timeout = 0.7; //avoid annoyance, don't request soon after editing } void EditorScriptEditorDebugger::_scene_tree_property_select_object(ObjectID p_object) { inspected_object_id = p_object; Array msg; msg.push_back("inspect_object"); msg.push_back(process_main_thread_id); msg.push_back(inspected_object_id); ppeer->put_var(msg); } void EditorScriptEditorDebugger::_scene_tree_request() { ERR_FAIL_COND(connection.is_null()); ERR_FAIL_COND(!connection->is_connected_to_host()); Array msg; msg.push_back("request_scene_tree"); msg.push_back(process_main_thread_id); ppeer->put_var(msg); } /// Populates inspect_scene_tree recursively given data in nodes. /// Nodes is an array containing 4 elements for each node, it follows this pattern: /// nodes[i] == number of direct children of this node /// nodes[i + 1] == node name /// nodes[i + 2] == node class /// nodes[i + 3] == node instance id /// /// Returns the number of items parsed in nodes from current_index. /// /// Given a nodes array like [R,A,B,C,D,E] the following Tree will be generated, assuming /// filter is an empty String, R and A child count are 2, B is 1 and C, D and E are 0. /// /// R /// |-A /// | |-B /// | | |-C /// | | /// | |-D /// | /// |-E /// int EditorScriptEditorDebugger::_update_scene_tree(TreeItem *parent, const Array &nodes, int current_index) { String filter = EditorNode::get_singleton()->get_scene_tree_dock()->get_filter(); String item_text = nodes[current_index + 1]; String item_type = nodes[current_index + 2]; bool keep = filter.is_subsequence_ofi(item_text); TreeItem *item = inspect_scene_tree->create_item(parent); item->set_text(0, item_text); item->set_tooltip(0, TTR("Type:") + " " + item_type); ObjectID id = ObjectID(nodes[current_index + 3]); Ref icon = EditorNode::get_singleton()->get_class_icon(nodes[current_index + 2], ""); if (icon.is_valid()) { item->set_icon(0, icon); } item->set_metadata(0, id); bool scroll = false; if (id == inspected_object_id) { TreeItem *cti = item->get_parent(); while (cti) { cti->set_collapsed(false); cti = cti->get_parent(); } item->select(0); scroll = filter != last_filter; } // Set current item as collapsed if necessary if (parent) { if (!unfold_cache.has(id)) { item->set_collapsed(true); } } int children_count = nodes[current_index]; // Tracks the total number of items parsed in nodes, this is used to skips nodes that // are not direct children of the current node since we can't know in advance the total // number of children, direct and not, of a node without traversing the nodes array previously. // Keeping track of this allows us to build our remote scene tree by traversing the node // array just once. int items_count = 1; for (int i = 0; i < children_count; i++) { // Called for each direct child of item. // Direct children of current item might not be adjacent so items_count must // be incremented by the number of items parsed until now, otherwise we would not // be able to access the next child of the current item. // items_count is multiplied by 4 since that's the number of elements in the nodes // array needed to represent a single node. items_count += _update_scene_tree(item, nodes, current_index + items_count * 4); } // If item has not children and should not be kept delete it if (!keep && !item->get_children() && parent) { parent->remove_child(item); memdelete(item); } else if (scroll) { inspect_scene_tree->call_deferred("scroll_to_item", item); } if (!parent) { last_filter = filter; } return items_count; } void EditorScriptEditorDebugger::_video_mem_request() { if (connection.is_null() || !connection->is_connected_to_host()) { // Video RAM usage is only available while a project is being debugged. return; } Array msg; msg.push_back("request_video_mem"); msg.push_back(process_main_thread_id); ppeer->put_var(msg); } void EditorScriptEditorDebugger::_video_mem_export() { file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM); file_dialog->clear_filters(); file_dialog_mode = SAVE_VRAM_CSV; file_dialog->popup_centered_ratio(); } Size2 EditorScriptEditorDebugger::get_minimum_size() const { Size2 ms = MarginContainer::get_minimum_size(); ms.y = MAX(ms.y, 250 * EDSCALE); return ms; } void EditorScriptEditorDebugger::_thread_debug_enter(uint64_t p_thread_id) { ERR_FAIL_COND(!threads_debugged.has(p_thread_id)); ThreadDebugged &td = threads_debugged[p_thread_id]; _set_reason_text(td.error, MESSAGE_ERROR); emit_signal("breaked", true, td.can_debug, td.error, td.has_stackdump); if (!td.error.empty()) { tabs->set_current_tab(0); } inspector->refresh(); // Take a chance to force remote objects update. Array msg; msg.push_back("get_stack_dump"); msg.push_back(p_thread_id); ppeer->put_var(msg); } void EditorScriptEditorDebugger::_select_thread(int p_index) { debugging_thread_id = threads->get_item_metadata(threads->get_selected()); _thread_debug_enter(debugging_thread_id); } void EditorScriptEditorDebugger::_parse_message(const String &p_msg, uint64_t p_thread_id, const Array &p_data) { if (p_msg == "debug_enter") { /* Array msg; msg.push_back("get_stack_dump"); ppeer->put_var(msg); ERR_FAIL_COND(p_data.size() != 2); bool can_continue = p_data[0]; String error = p_data[1]; step->set_disabled(!can_continue); next->set_disabled(!can_continue); _set_reason_text(error, MESSAGE_ERROR); copy->set_disabled(false); breaked = true; dobreak->set_disabled(true); docontinue->set_disabled(false); emit_signal("breaked", true, can_continue); OS::get_singleton()->move_window_to_foreground(); if (error != "") { tabs->set_current_tab(0); } */ ERR_FAIL_COND(p_data.size() != 4); ThreadDebugged td; td.name = p_data[3]; td.error = p_data[1]; td.can_debug = p_data[0]; td.has_stackdump = p_data[2]; td.thread_id = p_thread_id; static uint32_t order_inc = 0; td.debug_order = order_inc++; threads_debugged.insert(p_thread_id, td); if (threads_debugged.size() == 1) { // First thread that requests debug debugging_thread_id = p_thread_id; _thread_debug_enter(p_thread_id); bool can_continue = p_data[0]; String error = p_data[1]; step->set_disabled(!can_continue); next->set_disabled(!can_continue); _set_reason_text(error, MESSAGE_ERROR); copy->set_disabled(false); dobreak->set_disabled(true); docontinue->set_disabled(false); OS::get_singleton()->move_window_to_foreground(); if (reason->get_text() != "") { tabs->set_current_tab(0); } } profiler->set_enabled(false); EditorNode::get_singleton()->get_pause_button()->set_pressed(true); EditorNode::get_singleton()->make_bottom_panel_item_visible(this); _clear_remote_objects(); _update_buttons_state(); } else if (p_msg == "debug_exit") { /* breaked = false; _clear_execution(); copy->set_disabled(true); step->set_disabled(true); next->set_disabled(true); reason->set_text(""); reason->set_tooltip(""); back->set_disabled(true); forward->set_disabled(true); dobreak->set_disabled(false); docontinue->set_disabled(true); emit_signal("breaked", false, false, Variant()); */ threads_debugged.erase(p_thread_id); if (p_thread_id == debugging_thread_id) { _clear_execution(); if (threads_debugged.size() == 0) { debugging_thread_id = 0; } else { // Find next thread to debug. uint32_t min_order = 0xFFFFFFFF; uint64_t next_thread = 0; for (HashMap::Element *T = threads_debugged.front(); T; T = T->next) { if (T->value().debug_order < min_order) { min_order = T->value().debug_order; next_thread = T->key(); } } debugging_thread_id = next_thread; } if (debugging_thread_id == 0) { // Nothing else to debug. copy->set_disabled(true); step->set_disabled(true); next->set_disabled(true); reason->set_text(""); reason->set_tooltip(""); back->set_disabled(true); forward->set_disabled(true); dobreak->set_disabled(false); docontinue->set_disabled(true); _set_reason_text(TTR("Execution resumed."), MESSAGE_SUCCESS); emit_signal("breaked", false, false, "", false); _update_buttons_state(); } else { _thread_debug_enter(debugging_thread_id); } } else { _update_buttons_state(); } profiler->set_enabled(true); profiler->disable_seeking(); EditorNode::get_singleton()->get_pause_button()->set_pressed(false); } else if (p_msg == "message:click_ctrl") { clicked_ctrl->set_text(p_data[0]); clicked_ctrl_type->set_text(p_data[1]); } else if (p_msg == "message:scene_tree") { inspect_scene_tree->clear(); RBMap lv; updating_scene_tree = true; _update_scene_tree(nullptr, p_data, 0); updating_scene_tree = false; le_clear->set_disabled(false); le_set->set_disabled(false); } else if (p_msg == "message:inspect_object") { EditorScriptEditorDebuggerInspectedObject *debug_obj = nullptr; ObjectID id = p_data[0]; String type = p_data[1]; Array properties = p_data[2]; if (remote_objects.has(id)) { debug_obj = remote_objects[id]; } else { debug_obj = memnew(EditorScriptEditorDebuggerInspectedObject); debug_obj->remote_object_id = id; debug_obj->type_name = type; remote_objects[id] = debug_obj; debug_obj->connect("value_edited", this, "_scene_tree_property_value_edited"); } int old_prop_size = debug_obj->prop_list.size(); debug_obj->prop_list.clear(); int new_props_added = 0; RBSet changed; for (int i = 0; i < properties.size(); i++) { Array prop = properties[i]; if (prop.size() != 6) { continue; } PropertyInfo pinfo; pinfo.name = prop[0]; pinfo.type = Variant::Type(int(prop[1])); pinfo.hint = PropertyHint(int(prop[2])); pinfo.hint_string = prop[3]; pinfo.usage = PropertyUsageFlags(int(prop[4])); Variant var = prop[5]; if (pinfo.type == Variant::OBJECT) { if (var.is_zero()) { var = RES(); } else if (var.get_type() == Variant::STRING) { String path = var; if (path.find("::") != -1) { // built-in resource String base_path = path.get_slice("::", 0); RES dependency = ResourceLoader::load(base_path); if (dependency.is_valid()) { remote_dependencies.insert(dependency); } } var = ResourceLoader::load(path); if (pinfo.hint_string == "Script") { if (debug_obj->get_script() != var) { debug_obj->set_script(RefPtr()); Ref