Path: blob/master/modules/objectdb_profiler/editor/objectdb_profiler_panel.cpp
11323 views
/**************************************************************************/1/* objectdb_profiler_panel.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "objectdb_profiler_panel.h"3132#include "../snapshot_collector.h"33#include "data_viewers/class_view.h"34#include "data_viewers/node_view.h"35#include "data_viewers/object_view.h"36#include "data_viewers/refcounted_view.h"37#include "data_viewers/summary_view.h"3839#include "core/config/project_settings.h"40#include "core/os/time.h"41#include "editor/debugger/editor_debugger_node.h"42#include "editor/debugger/script_editor_debugger.h"43#include "editor/editor_node.h"44#include "editor/themes/editor_scale.h"45#include "scene/gui/button.h"46#include "scene/gui/label.h"47#include "scene/gui/option_button.h"48#include "scene/gui/split_container.h"49#include "scene/gui/tab_container.h"5051// ObjectDB snapshots are very large. In remote_debugger_peer.cpp, the max in_buf and out_buf size is 8mb.52// Snapshots are typically larger than that, so we send them 6mb at a time. Leaving 2mb for other data.53const int SNAPSHOT_CHUNK_SIZE = 6 << 20;5455void ObjectDBProfilerPanel::_request_object_snapshot() {56take_snapshot->set_disabled(true);57take_snapshot->set_text(TTRC("Generating Snapshot"));58// Pause the game while the snapshot is taken so the state of the game isn't modified as we capture the snapshot.59if (EditorDebuggerNode::get_singleton()->get_current_debugger()->is_breaked()) {60requested_break_for_snapshot = false;61_begin_object_snapshot();62} else {63awaiting_debug_break = true;64requested_break_for_snapshot = true; // We only need to resume the game if we are the ones who paused it.65EditorDebuggerNode::get_singleton()->debug_break();66}67}6869void ObjectDBProfilerPanel::_on_debug_breaked(bool p_reallydid, bool p_can_debug, const String &p_reason, bool p_has_stackdump) {70if (p_reallydid && awaiting_debug_break) {71awaiting_debug_break = false;72_begin_object_snapshot();73}74}7576void ObjectDBProfilerPanel::_begin_object_snapshot() {77Array args = { next_request_id++, SnapshotCollector::get_godot_version_string() };78EditorDebuggerNode::get_singleton()->get_current_debugger()->send_message("snapshot:request_prepare_snapshot", args);79}8081bool ObjectDBProfilerPanel::handle_debug_message(const String &p_message, const Array &p_data, int p_index) {82if (p_message == "snapshot:snapshot_prepared") {83int request_id = p_data[0];84int total_size = p_data[1];85partial_snapshots[request_id] = PartialSnapshot();86partial_snapshots[request_id].total_size = total_size;87Array args = { request_id, 0, SNAPSHOT_CHUNK_SIZE };88take_snapshot->set_text(vformat(TTRC("Receiving Snapshot (0/%s MiB)"), _to_mb(total_size)));89EditorDebuggerNode::get_singleton()->get_current_debugger()->send_message("snapshot:request_snapshot_chunk", args);90return true;91}92if (p_message == "snapshot:snapshot_chunk") {93int request_id = p_data[0];94PartialSnapshot &chunk = partial_snapshots[request_id];95chunk.data.append_array(p_data[1]);96take_snapshot->set_text(vformat(TTRC("Receiving Snapshot (%s/%s MiB)"), _to_mb(chunk.data.size()), _to_mb(chunk.total_size)));97if (chunk.data.size() != chunk.total_size) {98Array args = { request_id, chunk.data.size(), chunk.data.size() + SNAPSHOT_CHUNK_SIZE };99EditorDebuggerNode::get_singleton()->get_current_debugger()->send_message("snapshot:request_snapshot_chunk", args);100return true;101}102103take_snapshot->set_text(TTRC("Visualizing Snapshot"));104// Wait a frame just so the button has a chance to update its text so the user knows what's going on.105get_tree()->connect("process_frame", callable_mp(this, &ObjectDBProfilerPanel::receive_snapshot).bind(request_id), CONNECT_ONE_SHOT);106return true;107}108return false;109}110111void ObjectDBProfilerPanel::receive_snapshot(int request_id) {112const Vector<uint8_t> &in_data = partial_snapshots[request_id].data;113String snapshot_file_name = Time::get_singleton()->get_datetime_string_from_system(false).replace_char('T', '_').replace_char(':', '-');114Ref<DirAccess> snapshot_dir = _get_and_create_snapshot_storage_dir();115if (snapshot_dir.is_valid()) {116Error err;117String current_dir = snapshot_dir->get_current_dir();118String joined_dir = current_dir.path_join(snapshot_file_name) + ".odb_snapshot";119120Ref<FileAccess> file = FileAccess::open(joined_dir, FileAccess::WRITE, &err);121if (err == OK) {122file->store_buffer(in_data);123file->close(); // RAII could do this typically, but we want to read the file in _show_selected_snapshot, so we have to finalize the write before that.124125_add_snapshot_button(snapshot_file_name, joined_dir);126snapshot_list->deselect_all();127snapshot_list->set_selected(snapshot_list->get_root()->get_first_child());128snapshot_list->ensure_cursor_is_visible();129_show_selected_snapshot();130} else {131ERR_PRINT("Could not persist ObjectDB Snapshot: " + String(error_names[err]));132}133}134partial_snapshots.erase(request_id);135if (requested_break_for_snapshot) {136EditorDebuggerNode::get_singleton()->debug_continue();137}138take_snapshot->set_disabled(false);139take_snapshot->set_text("Take ObjectDB Snapshot");140}141142Ref<DirAccess> ObjectDBProfilerPanel::_get_and_create_snapshot_storage_dir() {143String profiles_dir = "user://";144Ref<DirAccess> da = DirAccess::open(profiles_dir);145ERR_FAIL_COND_V_MSG(da.is_null(), nullptr, vformat("Could not open 'user://' directory: '%s'.", profiles_dir));146Error err = da->change_dir("objectdb_snapshots");147if (err != OK) {148Error err_mk = da->make_dir("objectdb_snapshots");149Error err_ch = da->change_dir("objectdb_snapshots");150ERR_FAIL_COND_V_MSG(err_mk != OK || err_ch != OK, nullptr, "Could not create ObjectDB Snapshots directory: " + da->get_current_dir());151}152return da;153}154155TreeItem *ObjectDBProfilerPanel::_add_snapshot_button(const String &p_snapshot_file_name, const String &p_full_file_path) {156TreeItem *item = snapshot_list->create_item(snapshot_list->get_root());157item->set_text(0, p_snapshot_file_name);158item->set_metadata(0, p_full_file_path);159item->set_auto_translate_mode(0, AUTO_TRANSLATE_MODE_DISABLED);160item->move_before(snapshot_list->get_root()->get_first_child());161_update_diff_items();162_update_enabled_diff_items();163return item;164}165166void ObjectDBProfilerPanel::_show_selected_snapshot() {167if (snapshot_list->get_selected()->get_text(0) == (String)diff_button->get_selected_metadata()) {168for (int i = 0; i < diff_button->get_item_count(); i++) {169if (diff_button->get_item_text(i) == current_snapshot->get_snapshot()->name) {170diff_button->select(i);171break;172}173}174}175show_snapshot(snapshot_list->get_selected()->get_text(0), diff_button->get_selected_metadata());176_update_enabled_diff_items();177}178179void ObjectDBProfilerPanel::_on_snapshot_deselected() {180snapshot_list->deselect_all();181diff_button->select(0);182clear_snapshot();183_update_enabled_diff_items();184}185186Ref<GameStateSnapshotRef> ObjectDBProfilerPanel::get_snapshot(const String &p_snapshot_file_name) {187if (snapshot_cache.has(p_snapshot_file_name)) {188return snapshot_cache.get(p_snapshot_file_name);189}190191Ref<DirAccess> snapshot_dir = _get_and_create_snapshot_storage_dir();192ERR_FAIL_COND_V_MSG(snapshot_dir.is_null(), nullptr, "Could not access ObjectDB Snapshot directory");193194String full_file_path = snapshot_dir->get_current_dir().path_join(p_snapshot_file_name) + ".odb_snapshot";195196Error err;197Ref<FileAccess> snapshot_file = FileAccess::open(full_file_path, FileAccess::READ, &err);198ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Could not open ObjectDB Snapshot file: " + full_file_path);199200Vector<uint8_t> content = snapshot_file->get_buffer(snapshot_file->get_length()); // We want to split on newlines, so normalize them.201ERR_FAIL_COND_V_MSG(content.is_empty(), nullptr, "ObjectDB Snapshot file is empty: " + full_file_path);202203Ref<GameStateSnapshotRef> snapshot = GameStateSnapshot::create_ref(p_snapshot_file_name, content);204if (snapshot.is_valid()) {205snapshot_cache.insert(p_snapshot_file_name, snapshot);206}207208return snapshot;209}210211void ObjectDBProfilerPanel::show_snapshot(const String &p_snapshot_file_name, const String &p_snapshot_diff_file_name) {212clear_snapshot(false);213214current_snapshot = get_snapshot(p_snapshot_file_name);215if (!p_snapshot_diff_file_name.is_empty()) {216diff_snapshot = get_snapshot(p_snapshot_diff_file_name);217}218219_update_view_tabs();220_view_tab_changed(view_tabs->get_current_tab());221}222223void ObjectDBProfilerPanel::_view_tab_changed(int p_tab_idx) {224// Populating tabs only on tab changed because we're handling a lot of data,225// and the editor freezes for a while if we try to populate every tab at once.226SnapshotView *view = cast_to<SnapshotView>(view_tabs->get_current_tab_control());227GameStateSnapshot *snapshot = current_snapshot.is_null() ? nullptr : current_snapshot->get_snapshot();228GameStateSnapshot *diff = diff_snapshot.is_null() ? nullptr : diff_snapshot->get_snapshot();229if (snapshot != nullptr && !view->is_showing_snapshot(snapshot, diff)) {230view->show_snapshot(snapshot, diff);231}232}233234void ObjectDBProfilerPanel::clear_snapshot(bool p_update_view_tabs) {235for (SnapshotView *view : views) {236view->clear_snapshot();237}238239current_snapshot.unref();240diff_snapshot.unref();241242if (p_update_view_tabs) {243_update_view_tabs();244}245}246247void ObjectDBProfilerPanel::set_enabled(bool p_enabled) {248take_snapshot->set_text(TTRC("Take ObjectDB Snapshot"));249take_snapshot->set_disabled(!p_enabled);250}251252void ObjectDBProfilerPanel::_snapshot_rmb(const Vector2 &p_pos, MouseButton p_button) {253if (p_button != MouseButton::RIGHT) {254return;255}256rmb_menu->clear(false);257258rmb_menu->add_icon_item(get_editor_theme_icon(SNAME("Rename")), TTRC("Rename"), OdbProfilerMenuOptions::ODB_MENU_RENAME);259rmb_menu->add_icon_item(get_editor_theme_icon(SNAME("Folder")), TTRC("Show in File Manager"), OdbProfilerMenuOptions::ODB_MENU_SHOW_IN_FOLDER);260rmb_menu->add_icon_item(get_editor_theme_icon(SNAME("Remove")), TTRC("Delete"), OdbProfilerMenuOptions::ODB_MENU_DELETE);261262rmb_menu->set_position(snapshot_list->get_screen_position() + p_pos);263rmb_menu->reset_size();264rmb_menu->popup();265}266267void ObjectDBProfilerPanel::_rmb_menu_pressed(int p_tool, bool p_confirm_override) {268String file_path = snapshot_list->get_selected()->get_metadata(0);269String global_path = ProjectSettings::get_singleton()->globalize_path(file_path);270switch (rmb_menu->get_item_id(p_tool)) {271case OdbProfilerMenuOptions::ODB_MENU_SHOW_IN_FOLDER: {272OS::get_singleton()->shell_show_in_file_manager(global_path, true);273break;274}275case OdbProfilerMenuOptions::ODB_MENU_DELETE: {276DirAccess::remove_file_or_error(global_path);277snapshot_list->get_root()->remove_child(snapshot_list->get_selected());278if (snapshot_list->get_root()->get_child_count() > 0) {279snapshot_list->set_selected(snapshot_list->get_root()->get_first_child());280} else {281// If we deleted the last snapshot, jump back to the summary tab and clear everything out.282clear_snapshot();283}284_update_diff_items();285break;286}287case OdbProfilerMenuOptions::ODB_MENU_RENAME: {288snapshot_list->edit_selected(true);289break;290}291}292}293294void ObjectDBProfilerPanel::_edit_snapshot_name() {295String new_snapshot_name = snapshot_list->get_selected()->get_text(0);296String full_file_with_path = snapshot_list->get_selected()->get_metadata(0);297Vector<String> full_path_parts = full_file_with_path.rsplit("/", false, 1);298String full_file_path = full_path_parts[0];299String file_name = full_path_parts[1];300String old_snapshot_name = file_name.split(".")[0];301String new_full_file_path = full_file_path.path_join(new_snapshot_name) + ".odb_snapshot";302303bool name_taken = false;304for (int i = 0; i < snapshot_list->get_root()->get_child_count(); i++) {305TreeItem *item = snapshot_list->get_root()->get_child(i);306if (item != snapshot_list->get_selected()) {307if (item->get_text(0) == new_snapshot_name) {308name_taken = true;309break;310}311}312}313314if (name_taken || new_snapshot_name.contains_char(':') || new_snapshot_name.contains_char('\\') || new_snapshot_name.contains_char('/') || new_snapshot_name.begins_with(".") || new_snapshot_name.is_empty()) {315EditorNode::get_singleton()->show_warning(TTRC("Invalid snapshot name."));316snapshot_list->get_selected()->set_text(0, old_snapshot_name);317return;318}319320Error err = DirAccess::rename_absolute(full_file_with_path, new_full_file_path);321if (err != OK) {322EditorNode::get_singleton()->show_warning(TTRC("Snapshot rename failed"));323snapshot_list->get_selected()->set_text(0, old_snapshot_name);324} else {325snapshot_list->get_selected()->set_metadata(0, new_full_file_path);326}327328_update_diff_items();329_show_selected_snapshot();330}331332ObjectDBProfilerPanel::ObjectDBProfilerPanel() {333set_name(TTRC("ObjectDB Profiler"));334335snapshot_cache = LRUCache<String, Ref<GameStateSnapshotRef>>(SNAPSHOT_CACHE_MAX_SIZE);336337EditorDebuggerNode::get_singleton()->get_current_debugger()->connect("breaked", callable_mp(this, &ObjectDBProfilerPanel::_on_debug_breaked));338339HSplitContainer *root_container = memnew(HSplitContainer);340root_container->set_anchors_preset(Control::LayoutPreset::PRESET_FULL_RECT);341root_container->set_v_size_flags(Control::SizeFlags::SIZE_EXPAND_FILL);342root_container->set_h_size_flags(Control::SizeFlags::SIZE_EXPAND_FILL);343root_container->set_split_offset(300 * EDSCALE);344add_child(root_container);345346VBoxContainer *snapshot_column = memnew(VBoxContainer);347root_container->add_child(snapshot_column);348349take_snapshot = memnew(Button(TTRC("Take ObjectDB Snapshot")));350snapshot_column->add_child(take_snapshot);351take_snapshot->connect(SceneStringName(pressed), callable_mp(this, &ObjectDBProfilerPanel::_request_object_snapshot));352353snapshot_list = memnew(Tree);354snapshot_list->create_item();355snapshot_list->set_hide_folding(true);356snapshot_column->add_child(snapshot_list);357snapshot_list->set_select_mode(Tree::SelectMode::SELECT_ROW);358snapshot_list->set_hide_root(true);359snapshot_list->set_columns(1);360snapshot_list->set_column_titles_visible(true);361snapshot_list->set_column_title(0, "Snapshots");362snapshot_list->set_column_expand(0, true);363snapshot_list->set_column_clip_content(0, true);364snapshot_list->connect(SceneStringName(item_selected), callable_mp(this, &ObjectDBProfilerPanel::_show_selected_snapshot));365snapshot_list->connect("nothing_selected", callable_mp(this, &ObjectDBProfilerPanel::_on_snapshot_deselected));366snapshot_list->connect("item_edited", callable_mp(this, &ObjectDBProfilerPanel::_edit_snapshot_name));367snapshot_list->set_h_size_flags(SizeFlags::SIZE_EXPAND_FILL);368snapshot_list->set_v_size_flags(SizeFlags::SIZE_EXPAND_FILL);369snapshot_list->set_anchors_preset(LayoutPreset::PRESET_FULL_RECT);370371snapshot_list->set_allow_rmb_select(true);372snapshot_list->connect("item_mouse_selected", callable_mp(this, &ObjectDBProfilerPanel::_snapshot_rmb));373374rmb_menu = memnew(PopupMenu);375add_child(rmb_menu);376rmb_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ObjectDBProfilerPanel::_rmb_menu_pressed).bind(false));377378HBoxContainer *diff_button_and_label = memnew(HBoxContainer);379diff_button_and_label->set_h_size_flags(SizeFlags::SIZE_EXPAND_FILL);380snapshot_column->add_child(diff_button_and_label);381Label *diff_against = memnew(Label(TTRC("Diff Against:")));382diff_button_and_label->add_child(diff_against);383384diff_button = memnew(OptionButton);385diff_button->set_h_size_flags(SizeFlags::SIZE_EXPAND_FILL);386diff_button->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);387diff_button->connect(SceneStringName(item_selected), callable_mp(this, &ObjectDBProfilerPanel::_show_selected_snapshot).unbind(1));388diff_button_and_label->add_child(diff_button);389390// Tabs of various views right for each snapshot.391view_tabs = memnew(TabContainer);392root_container->add_child(view_tabs);393view_tabs->set_custom_minimum_size(Size2(300 * EDSCALE, 0));394view_tabs->set_v_size_flags(SizeFlags::SIZE_EXPAND_FILL);395view_tabs->connect("tab_changed", callable_mp(this, &ObjectDBProfilerPanel::_view_tab_changed));396397add_view(memnew(SnapshotSummaryView));398add_view(memnew(SnapshotClassView));399add_view(memnew(SnapshotObjectView));400add_view(memnew(SnapshotNodeView));401add_view(memnew(SnapshotRefCountedView));402403set_enabled(false);404405// Load all the snapshot names from disk.406Ref<DirAccess> snapshot_dir = _get_and_create_snapshot_storage_dir();407if (snapshot_dir.is_valid()) {408for (const String &file_name : snapshot_dir->get_files()) {409Vector<String> name_parts = file_name.split(".");410ERR_CONTINUE_MSG(name_parts.size() != 2 || name_parts[1] != "odb_snapshot", "ObjectDB snapshot file did not have .odb_snapshot extension. Skipping: " + file_name);411_add_snapshot_button(name_parts[0], snapshot_dir->get_current_dir().path_join(file_name));412}413}414}415416void ObjectDBProfilerPanel::add_view(SnapshotView *p_to_add) {417views.push_back(p_to_add);418view_tabs->add_child(p_to_add);419_update_view_tabs();420}421422void ObjectDBProfilerPanel::_update_view_tabs() {423bool has_snapshot = current_snapshot.is_valid();424for (int i = 1; i < view_tabs->get_tab_count(); i++) {425view_tabs->set_tab_disabled(i, !has_snapshot);426}427428if (!has_snapshot) {429view_tabs->set_current_tab(0);430}431}432433void ObjectDBProfilerPanel::_update_diff_items() {434diff_button->clear();435diff_button->add_item(TTRC("None"), 0);436diff_button->set_item_metadata(0, String());437diff_button->set_item_auto_translate_mode(0, Node::AUTO_TRANSLATE_MODE_ALWAYS);438439for (int i = 0; i < snapshot_list->get_root()->get_child_count(); i++) {440String name = snapshot_list->get_root()->get_child(i)->get_text(0);441diff_button->add_item(name);442diff_button->set_item_metadata(i + 1, name);443}444}445446void ObjectDBProfilerPanel::_update_enabled_diff_items() {447TreeItem *selected_snapshot = snapshot_list->get_selected();448if (selected_snapshot == nullptr) {449diff_button->set_disabled(true);450return;451}452453diff_button->set_disabled(false);454455String snapshot_name = selected_snapshot->get_text(0);456for (int i = 0; i < diff_button->get_item_count(); i++) {457diff_button->set_item_disabled(i, diff_button->get_item_text(i) == snapshot_name);458}459}460461String ObjectDBProfilerPanel::_to_mb(int p_x) {462return String::num((double)p_x / (double)(1 << 20), 2);463}464465466