Path: blob/master/editor/settings/editor_command_palette.cpp
20941 views
/**************************************************************************/1/* editor_command_palette.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 "editor_command_palette.h"3132#include "core/os/keyboard.h"33#include "editor/editor_node.h"34#include "editor/editor_string_names.h"35#include "editor/gui/editor_toaster.h"36#include "editor/gui/filter_line_edit.h"37#include "editor/settings/editor_settings.h"38#include "editor/themes/editor_scale.h"39#include "scene/gui/margin_container.h"40#include "scene/gui/tree.h"4142EditorCommandPalette *EditorCommandPalette::singleton = nullptr;4344static Rect2i prev_rect = Rect2i();45static bool was_showed = false;4647float EditorCommandPalette::_score_path(const String &p_search, const String &p_path) {48float score = 0.9f + .1f * (p_search.length() / (float)p_path.length());4950// Positive bias for matches close to the beginning of the file name.51int pos = p_path.findn(p_search);52if (pos != -1) {53return score * (1.0f - 0.1f * (float(pos) / p_path.length()));54}5556// Positive bias for matches close to the end of the path.57pos = p_path.rfindn(p_search);58if (pos != -1) {59return score * (0.8f - 0.1f * (float(p_path.length() - pos) / p_path.length()));60}6162// Remaining results belong to the same class of results.63return score * 0.69f;64}6566void EditorCommandPalette::_update_command_search(const String &search_text) {67ERR_FAIL_COND(commands.is_empty());6869HashMap<String, TreeItem *> sections;70TreeItem *first_section = nullptr;7172// Filter possible candidates.73Vector<CommandEntry> entries;74for (const KeyValue<String, Command> &E : commands) {75CommandEntry r;76r.key_name = E.key;77r.display_name = E.value.name;78r.shortcut_text = E.value.shortcut_text;79r.last_used = E.value.last_used;8081bool is_subsequence_of_key_name = search_text.is_subsequence_ofn(r.key_name);82bool is_subsequence_of_display_name = search_text.is_subsequence_ofn(r.display_name);8384if (is_subsequence_of_key_name || is_subsequence_of_display_name) {85if (!search_text.is_empty()) {86float key_name_score = is_subsequence_of_key_name ? _score_path(search_text, r.key_name.to_lower()) : .0f;87float display_name_score = is_subsequence_of_display_name ? _score_path(search_text, r.display_name.to_lower()) : .0f;8889r.score = MAX(key_name_score, display_name_score);90}9192entries.push_back(r);93}94}9596TreeItem *root = search_options->get_root();97root->clear_children();9899if (entries.is_empty()) {100get_ok_button()->set_disabled(true);101102return;103}104105if (!search_text.is_empty()) {106SortArray<CommandEntry, CommandEntryComparator> sorter;107sorter.sort(entries.ptrw(), entries.size());108} else {109SortArray<CommandEntry, CommandHistoryComparator> sorter;110sorter.sort(entries.ptrw(), entries.size());111}112113const int entry_limit = MIN(entries.size(), 300);114for (int i = 0; i < entry_limit; i++) {115String section_name = entries[i].key_name.get_slicec('/', 0);116TreeItem *section;117118if (sections.has(section_name)) {119section = sections[section_name];120} else {121section = search_options->create_item(root);122123if (!first_section) {124first_section = section;125}126127String item_name = section_name.capitalize();128section->set_text(0, item_name);129section->set_selectable(0, false);130section->set_selectable(1, false);131section->set_custom_bg_color(0, get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor)));132section->set_custom_bg_color(1, get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor)));133134sections[section_name] = section;135}136137TreeItem *ti = search_options->create_item(section);138String shortcut_text = entries[i].shortcut_text == "None" ? "" : entries[i].shortcut_text;139ti->set_text(0, entries[i].display_name);140ti->set_metadata(0, entries[i].key_name);141ti->set_text_alignment(1, HORIZONTAL_ALIGNMENT_RIGHT);142ti->set_text(1, shortcut_text);143Color c = get_theme_color(SceneStringName(font_color), EditorStringName(Editor)) * Color(1, 1, 1, 0.5);144ti->set_custom_color(1, c);145}146147TreeItem *to_select = first_section->get_first_child();148to_select->select(0);149to_select->set_as_cursor(0);150search_options->ensure_cursor_is_visible();151}152153void EditorCommandPalette::_bind_methods() {154ClassDB::bind_method(D_METHOD("add_command", "command_name", "key_name", "binded_callable", "shortcut_text"), &EditorCommandPalette::_add_command, DEFVAL("None"));155ClassDB::bind_method(D_METHOD("remove_command", "key_name"), &EditorCommandPalette::remove_command);156}157158void EditorCommandPalette::_notification(int p_what) {159switch (p_what) {160case NOTIFICATION_VISIBILITY_CHANGED: {161if (!is_visible()) {162prev_rect = Rect2i(get_position(), get_size());163was_showed = true;164}165} break;166167case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {168if (!EditorSettings::get_singleton()->check_changed_settings_in_group("shortcuts")) {169break;170}171172for (KeyValue<String, Command> &kv : commands) {173Command &c = kv.value;174if (c.shortcut.is_valid()) {175c.shortcut_text = c.shortcut->get_as_text();176}177}178} break;179}180}181182void EditorCommandPalette::_confirmed() {183TreeItem *selected_option = search_options->get_selected();184const String command_key = selected_option != nullptr ? selected_option->get_metadata(0) : "";185if (!command_key.is_empty()) {186hide();187callable_mp(this, &EditorCommandPalette::execute_command).call_deferred(command_key);188}189}190191void EditorCommandPalette::open_popup() {192if (was_showed) {193popup(prev_rect);194} else {195_update_command_search(String());196popup_centered_clamped(Size2(600, 440) * EDSCALE, 0.8f);197}198199command_search_box->clear();200command_search_box->grab_focus();201202search_options->scroll_to_item(search_options->get_root());203}204205void EditorCommandPalette::get_actions_list(List<String> *p_list) const {206for (const KeyValue<String, Command> &E : commands) {207p_list->push_back(E.key);208}209}210211void EditorCommandPalette::remove_command(String p_key_name) {212ERR_FAIL_COND_MSG(!commands.has(p_key_name), "The Command '" + String(p_key_name) + "' doesn't exists. Unable to remove it.");213214commands.erase(p_key_name);215}216217void EditorCommandPalette::add_command(String p_command_name, String p_key_name, Callable p_action, Vector<Variant> arguments, const Ref<Shortcut> &p_shortcut) {218ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");219220const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * arguments.size());221for (int i = 0; i < arguments.size(); i++) {222argptrs[i] = &arguments[i];223}224Command command;225command.name = p_command_name;226command.callable = p_action.bindp(argptrs, arguments.size());227if (p_shortcut.is_null()) {228command.shortcut_text = "None";229} else {230command.shortcut = p_shortcut;231command.shortcut_text = p_shortcut->get_as_text();232}233234commands[p_key_name] = command;235}236237void EditorCommandPalette::_add_command(String p_command_name, String p_key_name, Callable p_binded_action, String p_shortcut_text) {238ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");239240Command command;241command.name = p_command_name;242command.callable = p_binded_action;243command.shortcut_text = p_shortcut_text;244245// Commands added from plugins don't exist yet when the history is loaded, so we assign the last use time here if it was recorded.246Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());247if (command_history.has(p_key_name)) {248command.last_used = command_history[p_key_name];249}250251commands[p_key_name] = command;252}253254void EditorCommandPalette::execute_command(const String &p_command_key) {255ERR_FAIL_COND_MSG(!commands.has(p_command_key), p_command_key + " not found.");256commands[p_command_key].last_used = OS::get_singleton()->get_unix_time();257_save_history();258259Variant ret;260Callable::CallError ce;261const Callable &callable = commands[p_command_key].callable;262callable.callp(nullptr, 0, ret, ce);263264if (ce.error != Callable::CallError::CALL_OK) {265EditorToaster::get_singleton()->popup_str(vformat(TTR("Failed to execute command \"%s\":\n%s."), p_command_key, Variant::get_callable_error_text(callable, nullptr, 0, ce)), EditorToaster::SEVERITY_ERROR);266}267}268269void EditorCommandPalette::register_shortcuts_as_command() {270for (const KeyValue<String, Pair<String, Ref<Shortcut>>> &E : unregistered_shortcuts) {271String command_name = E.value.first;272Ref<Shortcut> shortcut = E.value.second;273Ref<InputEventShortcut> ev;274ev.instantiate();275ev->set_shortcut(shortcut);276add_command(command_name, E.key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), shortcut);277}278unregistered_shortcuts.clear();279280// Load command use history.281Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());282for (const KeyValue<Variant, Variant> &history_kv : command_history) {283const String &history_key = history_kv.key;284if (commands.has(history_key)) {285commands[history_key].last_used = history_kv.value;286}287}288}289290Ref<Shortcut> EditorCommandPalette::add_shortcut_command(const String &p_command, const String &p_key, Ref<Shortcut> p_shortcut) {291if (is_inside_tree()) {292Ref<InputEventShortcut> ev;293ev.instantiate();294ev->set_shortcut(p_shortcut);295add_command(p_command, p_key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), p_shortcut);296} else {297const String key_name = String(p_key);298const String command_name = String(p_command);299Pair pair = Pair(command_name, p_shortcut);300unregistered_shortcuts[key_name] = pair;301}302return p_shortcut;303}304305void EditorCommandPalette::_save_history() const {306Dictionary command_history;307308for (const KeyValue<String, Command> &E : commands) {309if (E.value.last_used > 0) {310command_history[E.key] = E.value.last_used;311}312}313EditorSettings::get_singleton()->set_project_metadata("command_palette", "command_history", command_history);314}315316EditorCommandPalette *EditorCommandPalette::get_singleton() {317if (singleton == nullptr) {318singleton = memnew(EditorCommandPalette);319}320return singleton;321}322323EditorCommandPalette::EditorCommandPalette() {324set_hide_on_ok(false);325connect(SceneStringName(confirmed), callable_mp(this, &EditorCommandPalette::_confirmed));326327VBoxContainer *vbc = memnew(VBoxContainer);328add_child(vbc);329330command_search_box = memnew(FilterLineEdit);331command_search_box->set_placeholder(TTRC("Filter Commands"));332command_search_box->set_accessibility_name(TTRC("Filter Commands"));333command_search_box->set_v_size_flags(Control::SIZE_EXPAND_FILL);334command_search_box->connect(SceneStringName(text_changed), callable_mp(this, &EditorCommandPalette::_update_command_search));335MarginContainer *margin_container_csb = memnew(MarginContainer);336margin_container_csb->add_child(command_search_box);337vbc->add_child(margin_container_csb);338register_text_enter(command_search_box);339340MarginContainer *mc = memnew(MarginContainer);341mc->set_theme_type_variation("NoBorderHorizontalWindow");342mc->set_v_size_flags(Control::SIZE_EXPAND_FILL);343mc->set_h_size_flags(Control::SIZE_EXPAND_FILL);344vbc->add_child(mc);345346search_options = memnew(Tree);347command_search_box->set_forward_control(search_options);348search_options->connect("item_activated", callable_mp(this, &EditorCommandPalette::_confirmed));349search_options->connect(SceneStringName(item_selected), callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(false));350search_options->connect("nothing_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(true));351search_options->create_item();352search_options->set_hide_root(true);353search_options->set_columns(2);354search_options->set_column_custom_minimum_width(0, int(8 * EDSCALE));355search_options->set_scroll_hint_mode(Tree::SCROLL_HINT_MODE_BOTH);356mc->add_child(search_options, true);357}358359Ref<Shortcut> ED_SHORTCUT_AND_COMMAND(const String &p_path, const String &p_name, Key p_keycode, String p_command_name) {360if (p_command_name.is_empty()) {361p_command_name = p_name;362}363364Ref<Shortcut> shortcut = ED_SHORTCUT(p_path, p_name, p_keycode);365EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);366return shortcut;367}368369Ref<Shortcut> ED_SHORTCUT_ARRAY_AND_COMMAND(const String &p_path, const String &p_name, const PackedInt32Array &p_keycodes, String p_command_name) {370if (p_command_name.is_empty()) {371p_command_name = p_name;372}373374Ref<Shortcut> shortcut = ED_SHORTCUT_ARRAY(p_path, p_name, p_keycodes);375EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);376return shortcut;377}378379380