Debian Codegraph @

editor/settings/editor_command_palette.cpp

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