editor_command_palette.cpp 14 KB

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