editor_command_palette.cpp 15 KB

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