1/**************************************************************************/
2/* editor_command_palette.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/editor_command_palette.h"
32#include "core/os/keyboard.h"
33#include "editor/editor_node.h"
34#include "editor/editor_scale.h"
35#include "editor/editor_settings.h"
36#include "editor/editor_string_names.h"
37#include "scene/gui/control.h"
38#include "scene/gui/tree.h"
39
40EditorCommandPalette *EditorCommandPalette::singleton = nullptr;
41
42static Rect2i prev_rect = Rect2i();
43static bool was_showed = false;
44
45float EditorCommandPalette::_score_path(const String &p_search, const String &p_path) {
46 float score = 0.9f + .1f * (p_search.length() / (float)p_path.length());
47
48 // Positive bias for matches close to the beginning of the file name.
49 int pos = p_path.findn(p_search);
50 if (pos != -1) {
51 return score * (1.0f - 0.1f * (float(pos) / p_path.length()));
52 }
53
54 // Positive bias for matches close to the end of the path.
55 pos = p_path.rfindn(p_search);
56 if (pos != -1) {
57 return score * (0.8f - 0.1f * (float(p_path.length() - pos) / p_path.length()));
58 }
59
60 // Remaining results belong to the same class of results.
61 return score * 0.69f;
62}
63
64void EditorCommandPalette::_update_command_search(const String &search_text) {
65 ERR_FAIL_COND(commands.size() == 0);
66
67 HashMap<String, TreeItem *> sections;
68 TreeItem *first_section = nullptr;
69
70 // Filter possible candidates.
71 Vector<CommandEntry> entries;
72 for (const KeyValue<String, Command> &E : commands) {
73 CommandEntry r;
74 r.key_name = E.key;
75 r.display_name = E.value.name;
76 r.shortcut_text = E.value.shortcut;
77 r.last_used = E.value.last_used;
78
79 bool is_subsequence_of_key_name = search_text.is_subsequence_ofn(r.key_name);
80 bool is_subsequence_of_display_name = search_text.is_subsequence_ofn(r.display_name);
81
82 if (is_subsequence_of_key_name || is_subsequence_of_display_name) {
83 if (!search_text.is_empty()) {
84 float key_name_score = is_subsequence_of_key_name ? _score_path(search_text, r.key_name.to_lower()) : .0f;
85 float display_name_score = is_subsequence_of_display_name ? _score_path(search_text, r.display_name.to_lower()) : .0f;
86
87 r.score = MAX(key_name_score, display_name_score);
88 }
89
90 entries.push_back(r);
91 }
92 }
93
94 command_keys.clear();
95
96 TreeItem *root = search_options->get_root();
97 root->clear_children();
98
99 if (entries.is_empty()) {
100 get_ok_button()->set_disabled(true);
101
102 return;
103 }
104
105 if (!search_text.is_empty()) {
106 SortArray<CommandEntry, CommandEntryComparator> sorter;
107 sorter.sort(entries.ptrw(), entries.size());
108 } else {
109 SortArray<CommandEntry, CommandHistoryComparator> sorter;
110 sorter.sort(entries.ptrw(), entries.size());
111 }
112
113 const int entry_limit = MIN(entries.size(), 300);
114 for (int i = 0; i < entry_limit; i++) {
115 String section_name = entries[i].key_name.get_slice("/", 0);
116 TreeItem *section;
117
118 if (sections.has(section_name)) {
119 section = sections[section_name];
120 } else {
121 section = search_options->create_item(root);
122
123 if (!first_section) {
124 first_section = section;
125 }
126
127 String item_name = section_name.capitalize();
128 section->set_text(0, item_name);
129 section->set_selectable(0, false);
130 section->set_selectable(1, false);
131 section->set_custom_bg_color(0, search_options->get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor)));
132 section->set_custom_bg_color(1, search_options->get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor)));
133
134 sections[section_name] = section;
135 }
136
137 TreeItem *ti = search_options->create_item(section);
138 String shortcut_text = entries[i].shortcut_text == "None" ? "" : entries[i].shortcut_text;
139 ti->set_text(0, entries[i].display_name);
140 ti->set_metadata(0, entries[i].key_name);
141 ti->set_text_alignment(1, HORIZONTAL_ALIGNMENT_RIGHT);
142 ti->set_text(1, shortcut_text);
143 Color c = get_theme_color(SNAME("font_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.5);
144 ti->set_custom_color(1, c);
145 }
146
147 TreeItem *to_select = first_section->get_first_child();
148 to_select->select(0);
149 to_select->set_as_cursor(0);
150 search_options->ensure_cursor_is_visible();
151}
152
153void EditorCommandPalette::_bind_methods() {
154 ClassDB::bind_method(D_METHOD("add_command", "command_name", "key_name", "binded_callable", "shortcut_text"), &EditorCommandPalette::_add_command, DEFVAL("None"));
155 ClassDB::bind_method(D_METHOD("remove_command", "key_name"), &EditorCommandPalette::remove_command);
156}
157
158void EditorCommandPalette::_notification(int p_what) {
159 switch (p_what) {
160 case NOTIFICATION_VISIBILITY_CHANGED: {
161 if (!is_visible()) {
162 prev_rect = Rect2i(get_position(), get_size());
163 was_showed = true;
164 }
165 } break;
166 }
167}
168
169void EditorCommandPalette::_sbox_input(const Ref<InputEvent> &p_ie) {
170 Ref<InputEventKey> k = p_ie;
171 if (k.is_valid()) {
172 switch (k->get_keycode()) {
173 case Key::UP:
174 case Key::DOWN:
175 case Key::PAGEUP:
176 case Key::PAGEDOWN: {
177 search_options->gui_input(k);
178 } break;
179 default:
180 break;
181 }
182 }
183}
184
185void EditorCommandPalette::_confirmed() {
186 TreeItem *selected_option = search_options->get_selected();
187 String command_key = selected_option != nullptr ? selected_option->get_metadata(0) : "";
188 if (!command_key.is_empty()) {
189 hide();
190 execute_command(command_key);
191 }
192}
193
194void EditorCommandPalette::open_popup() {
195 if (was_showed) {
196 popup(prev_rect);
197 } else {
198 popup_centered_clamped(Size2(600, 440) * EDSCALE, 0.8f);
199 }
200
201 command_search_box->clear();
202 command_search_box->grab_focus();
203
204 search_options->scroll_to_item(search_options->get_root());
205}
206
207void EditorCommandPalette::get_actions_list(List<String> *p_list) const {
208 for (const KeyValue<String, Command> &E : commands) {
209 p_list->push_back(E.key);
210 }
211}
212
213void EditorCommandPalette::remove_command(String p_key_name) {
214 ERR_FAIL_COND_MSG(!commands.has(p_key_name), "The Command '" + String(p_key_name) + "' doesn't exists. Unable to remove it.");
215
216 commands.erase(p_key_name);
217}
218
219void EditorCommandPalette::add_command(String p_command_name, String p_key_name, Callable p_action, Vector<Variant> arguments, String p_shortcut_text) {
220 ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
221
222 const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * arguments.size());
223 for (int i = 0; i < arguments.size(); i++) {
224 argptrs[i] = &arguments[i];
225 }
226 Command command;
227 command.name = p_command_name;
228 command.callable = p_action.bindp(argptrs, arguments.size());
229 command.shortcut = p_shortcut_text;
230
231 commands[p_key_name] = command;
232}
233
234void EditorCommandPalette::_add_command(String p_command_name, String p_key_name, Callable p_binded_action, String p_shortcut_text) {
235 ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
236
237 Command command;
238 command.name = p_command_name;
239 command.callable = p_binded_action;
240 command.shortcut = p_shortcut_text;
241
242 // 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.
243 Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
244 if (command_history.has(p_key_name)) {
245 command.last_used = command_history[p_key_name];
246 }
247
248 commands[p_key_name] = command;
249}
250
251void EditorCommandPalette::execute_command(String &p_command_key) {
252 ERR_FAIL_COND_MSG(!commands.has(p_command_key), p_command_key + " not found.");
253 commands[p_command_key].last_used = OS::get_singleton()->get_unix_time();
254 commands[p_command_key].callable.call_deferred();
255 _save_history();
256}
257
258void EditorCommandPalette::register_shortcuts_as_command() {
259 for (const KeyValue<String, Pair<String, Ref<Shortcut>>> &E : unregistered_shortcuts) {
260 String command_name = E.value.first;
261 Ref<Shortcut> shortcut = E.value.second;
262 Ref<InputEventShortcut> ev;
263 ev.instantiate();
264 ev->set_shortcut(shortcut);
265 String shortcut_text = String(shortcut->get_as_text());
266 add_command(command_name, E.key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), shortcut_text);
267 }
268 unregistered_shortcuts.clear();
269
270 // Load command use history.
271 Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
272 Array history_entries = command_history.keys();
273 for (int i = 0; i < history_entries.size(); i++) {
274 const String &history_key = history_entries[i];
275 if (commands.has(history_key)) {
276 commands[history_key].last_used = command_history[history_key];
277 }
278 }
279}
280
281Ref<Shortcut> EditorCommandPalette::add_shortcut_command(const String &p_command, const String &p_key, Ref<Shortcut> p_shortcut) {
282 if (is_inside_tree()) {
283 Ref<InputEventShortcut> ev;
284 ev.instantiate();
285 ev->set_shortcut(p_shortcut);
286 String shortcut_text = String(p_shortcut->get_as_text());
287 add_command(p_command, p_key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), shortcut_text);
288 } else {
289 const String key_name = String(p_key);
290 const String command_name = String(p_command);
291 Pair pair = Pair(command_name, p_shortcut);
292 unregistered_shortcuts[key_name] = pair;
293 }
294 return p_shortcut;
295}
296
297void EditorCommandPalette::_theme_changed() {
298 command_search_box->set_right_icon(search_options->get_editor_theme_icon(SNAME("Search")));
299}
300
301void EditorCommandPalette::_save_history() const {
302 Dictionary command_history;
303
304 for (const KeyValue<String, Command> &E : commands) {
305 if (E.value.last_used > 0) {
306 command_history[E.key] = E.value.last_used;
307 }
308 }
309 EditorSettings::get_singleton()->set_project_metadata("command_palette", "command_history", command_history);
310}
311
312EditorCommandPalette *EditorCommandPalette::get_singleton() {
313 if (singleton == nullptr) {
314 singleton = memnew(EditorCommandPalette);
315 }
316 return singleton;
317}
318
319EditorCommandPalette::EditorCommandPalette() {
320 set_hide_on_ok(false);
321 connect("confirmed", callable_mp(this, &EditorCommandPalette::_confirmed));
322
323 VBoxContainer *vbc = memnew(VBoxContainer);
324 vbc->connect("theme_changed", callable_mp(this, &EditorCommandPalette::_theme_changed));
325 add_child(vbc);
326
327 command_search_box = memnew(LineEdit);
328 command_search_box->set_placeholder(TTR("Filter Commands"));
329 command_search_box->connect("gui_input", callable_mp(this, &EditorCommandPalette::_sbox_input));
330 command_search_box->connect("text_changed", callable_mp(this, &EditorCommandPalette::_update_command_search));
331 command_search_box->set_v_size_flags(Control::SIZE_EXPAND_FILL);
332 command_search_box->set_clear_button_enabled(true);
333 MarginContainer *margin_container_csb = memnew(MarginContainer);
334 margin_container_csb->add_child(command_search_box);
335 vbc->add_child(margin_container_csb);
336 register_text_enter(command_search_box);
337
338 search_options = memnew(Tree);
339 search_options->connect("item_activated", callable_mp(this, &EditorCommandPalette::_confirmed));
340 search_options->connect("item_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(false));
341 search_options->connect("nothing_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(true));
342 search_options->create_item();
343 search_options->set_hide_root(true);
344 search_options->set_columns(2);
345 search_options->set_v_size_flags(Control::SIZE_EXPAND_FILL);
346 search_options->set_h_size_flags(Control::SIZE_EXPAND_FILL);
347 search_options->set_column_custom_minimum_width(0, int(8 * EDSCALE));
348 vbc->add_child(search_options, true);
349}
350
351Ref<Shortcut> ED_SHORTCUT_AND_COMMAND(const String &p_path, const String &p_name, Key p_keycode, String p_command_name) {
352 if (p_command_name.is_empty()) {
353 p_command_name = p_name;
354 }
355
356 Ref<Shortcut> shortcut = ED_SHORTCUT(p_path, p_name, p_keycode);
357 EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);
358 return shortcut;
359}
360