editor_command_palette.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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_settings.h"
  34. #include "editor/editor_string_names.h"
  35. #include "editor/gui/editor_toaster.h"
  36. #include "editor/themes/editor_scale.h"
  37. #include "scene/gui/control.h"
  38. #include "scene/gui/margin_container.h"
  39. #include "scene/gui/tree.h"
  40. EditorCommandPalette *EditorCommandPalette::singleton = nullptr;
  41. static Rect2i prev_rect = Rect2i();
  42. static bool was_showed = false;
  43. float EditorCommandPalette::_score_path(const String &p_search, const String &p_path) {
  44. float score = 0.9f + .1f * (p_search.length() / (float)p_path.length());
  45. // Positive bias for matches close to the beginning of the file name.
  46. int pos = p_path.findn(p_search);
  47. if (pos != -1) {
  48. return score * (1.0f - 0.1f * (float(pos) / p_path.length()));
  49. }
  50. // Positive bias for matches close to the end of the path.
  51. pos = p_path.rfindn(p_search);
  52. if (pos != -1) {
  53. return score * (0.8f - 0.1f * (float(p_path.length() - pos) / p_path.length()));
  54. }
  55. // Remaining results belong to the same class of results.
  56. return score * 0.69f;
  57. }
  58. void EditorCommandPalette::_update_command_search(const String &search_text) {
  59. ERR_FAIL_COND(commands.is_empty());
  60. HashMap<String, TreeItem *> sections;
  61. TreeItem *first_section = nullptr;
  62. // Filter possible candidates.
  63. Vector<CommandEntry> entries;
  64. for (const KeyValue<String, Command> &E : commands) {
  65. CommandEntry r;
  66. r.key_name = E.key;
  67. r.display_name = E.value.name;
  68. r.shortcut_text = E.value.shortcut_text;
  69. r.last_used = E.value.last_used;
  70. bool is_subsequence_of_key_name = search_text.is_subsequence_ofn(r.key_name);
  71. bool is_subsequence_of_display_name = search_text.is_subsequence_ofn(r.display_name);
  72. if (is_subsequence_of_key_name || is_subsequence_of_display_name) {
  73. if (!search_text.is_empty()) {
  74. float key_name_score = is_subsequence_of_key_name ? _score_path(search_text, r.key_name.to_lower()) : .0f;
  75. float display_name_score = is_subsequence_of_display_name ? _score_path(search_text, r.display_name.to_lower()) : .0f;
  76. r.score = MAX(key_name_score, display_name_score);
  77. }
  78. entries.push_back(r);
  79. }
  80. }
  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. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  143. if (!EditorSettings::get_singleton()->check_changed_settings_in_group("shortcuts")) {
  144. break;
  145. }
  146. for (KeyValue<String, Command> &kv : commands) {
  147. Command &c = kv.value;
  148. if (c.shortcut.is_valid()) {
  149. c.shortcut_text = c.shortcut->get_as_text();
  150. }
  151. }
  152. } break;
  153. }
  154. }
  155. void EditorCommandPalette::_sbox_input(const Ref<InputEvent> &p_ie) {
  156. Ref<InputEventKey> k = p_ie;
  157. if (k.is_valid()) {
  158. switch (k->get_keycode()) {
  159. case Key::UP:
  160. case Key::DOWN:
  161. case Key::PAGEUP:
  162. case Key::PAGEDOWN: {
  163. search_options->gui_input(k);
  164. } break;
  165. default:
  166. break;
  167. }
  168. }
  169. }
  170. void EditorCommandPalette::_confirmed() {
  171. TreeItem *selected_option = search_options->get_selected();
  172. const String command_key = selected_option != nullptr ? selected_option->get_metadata(0) : "";
  173. if (!command_key.is_empty()) {
  174. hide();
  175. callable_mp(this, &EditorCommandPalette::execute_command).call_deferred(command_key);
  176. }
  177. }
  178. void EditorCommandPalette::open_popup() {
  179. if (was_showed) {
  180. popup(prev_rect);
  181. } else {
  182. popup_centered_clamped(Size2(600, 440) * EDSCALE, 0.8f);
  183. }
  184. command_search_box->clear();
  185. command_search_box->grab_focus();
  186. search_options->scroll_to_item(search_options->get_root());
  187. }
  188. void EditorCommandPalette::get_actions_list(List<String> *p_list) const {
  189. for (const KeyValue<String, Command> &E : commands) {
  190. p_list->push_back(E.key);
  191. }
  192. }
  193. void EditorCommandPalette::remove_command(String p_key_name) {
  194. ERR_FAIL_COND_MSG(!commands.has(p_key_name), "The Command '" + String(p_key_name) + "' doesn't exists. Unable to remove it.");
  195. commands.erase(p_key_name);
  196. }
  197. void EditorCommandPalette::add_command(String p_command_name, String p_key_name, Callable p_action, Vector<Variant> arguments, const Ref<Shortcut> &p_shortcut) {
  198. ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
  199. const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * arguments.size());
  200. for (int i = 0; i < arguments.size(); i++) {
  201. argptrs[i] = &arguments[i];
  202. }
  203. Command command;
  204. command.name = p_command_name;
  205. command.callable = p_action.bindp(argptrs, arguments.size());
  206. if (p_shortcut.is_null()) {
  207. command.shortcut_text = "None";
  208. } else {
  209. command.shortcut = p_shortcut;
  210. command.shortcut_text = p_shortcut->get_as_text();
  211. }
  212. commands[p_key_name] = command;
  213. }
  214. void EditorCommandPalette::_add_command(String p_command_name, String p_key_name, Callable p_binded_action, String p_shortcut_text) {
  215. ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
  216. Command command;
  217. command.name = p_command_name;
  218. command.callable = p_binded_action;
  219. command.shortcut_text = p_shortcut_text;
  220. // 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.
  221. Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
  222. if (command_history.has(p_key_name)) {
  223. command.last_used = command_history[p_key_name];
  224. }
  225. commands[p_key_name] = command;
  226. }
  227. void EditorCommandPalette::execute_command(const String &p_command_key) {
  228. ERR_FAIL_COND_MSG(!commands.has(p_command_key), p_command_key + " not found.");
  229. commands[p_command_key].last_used = OS::get_singleton()->get_unix_time();
  230. _save_history();
  231. Variant ret;
  232. Callable::CallError ce;
  233. const Callable &callable = commands[p_command_key].callable;
  234. callable.callp(nullptr, 0, ret, ce);
  235. if (ce.error != Callable::CallError::CALL_OK) {
  236. 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);
  237. }
  238. }
  239. void EditorCommandPalette::register_shortcuts_as_command() {
  240. for (const KeyValue<String, Pair<String, Ref<Shortcut>>> &E : unregistered_shortcuts) {
  241. String command_name = E.value.first;
  242. Ref<Shortcut> shortcut = E.value.second;
  243. Ref<InputEventShortcut> ev;
  244. ev.instantiate();
  245. ev->set_shortcut(shortcut);
  246. add_command(command_name, E.key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), shortcut);
  247. }
  248. unregistered_shortcuts.clear();
  249. // Load command use history.
  250. Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
  251. Array history_entries = command_history.keys();
  252. for (int i = 0; i < history_entries.size(); i++) {
  253. const String &history_key = history_entries[i];
  254. if (commands.has(history_key)) {
  255. commands[history_key].last_used = command_history[history_key];
  256. }
  257. }
  258. }
  259. Ref<Shortcut> EditorCommandPalette::add_shortcut_command(const String &p_command, const String &p_key, Ref<Shortcut> p_shortcut) {
  260. if (is_inside_tree()) {
  261. Ref<InputEventShortcut> ev;
  262. ev.instantiate();
  263. ev->set_shortcut(p_shortcut);
  264. add_command(p_command, p_key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), p_shortcut);
  265. } else {
  266. const String key_name = String(p_key);
  267. const String command_name = String(p_command);
  268. Pair pair = Pair(command_name, p_shortcut);
  269. unregistered_shortcuts[key_name] = pair;
  270. }
  271. return p_shortcut;
  272. }
  273. void EditorCommandPalette::_save_history() const {
  274. Dictionary command_history;
  275. for (const KeyValue<String, Command> &E : commands) {
  276. if (E.value.last_used > 0) {
  277. command_history[E.key] = E.value.last_used;
  278. }
  279. }
  280. EditorSettings::get_singleton()->set_project_metadata("command_palette", "command_history", command_history);
  281. }
  282. EditorCommandPalette *EditorCommandPalette::get_singleton() {
  283. if (singleton == nullptr) {
  284. singleton = memnew(EditorCommandPalette);
  285. }
  286. return singleton;
  287. }
  288. EditorCommandPalette::EditorCommandPalette() {
  289. set_hide_on_ok(false);
  290. connect("confirmed", callable_mp(this, &EditorCommandPalette::_confirmed));
  291. VBoxContainer *vbc = memnew(VBoxContainer);
  292. add_child(vbc);
  293. command_search_box = memnew(LineEdit);
  294. command_search_box->set_placeholder(TTR("Filter Commands"));
  295. command_search_box->connect(SceneStringName(gui_input), callable_mp(this, &EditorCommandPalette::_sbox_input));
  296. command_search_box->connect("text_changed", callable_mp(this, &EditorCommandPalette::_update_command_search));
  297. command_search_box->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  298. command_search_box->set_clear_button_enabled(true);
  299. MarginContainer *margin_container_csb = memnew(MarginContainer);
  300. margin_container_csb->add_child(command_search_box);
  301. vbc->add_child(margin_container_csb);
  302. register_text_enter(command_search_box);
  303. search_options = memnew(Tree);
  304. search_options->connect("item_activated", callable_mp(this, &EditorCommandPalette::_confirmed));
  305. search_options->connect("item_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(false));
  306. search_options->connect("nothing_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(true));
  307. search_options->create_item();
  308. search_options->set_hide_root(true);
  309. search_options->set_columns(2);
  310. search_options->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  311. search_options->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  312. search_options->set_column_custom_minimum_width(0, int(8 * EDSCALE));
  313. vbc->add_child(search_options, true);
  314. }
  315. Ref<Shortcut> ED_SHORTCUT_AND_COMMAND(const String &p_path, const String &p_name, Key p_keycode, String p_command_name) {
  316. if (p_command_name.is_empty()) {
  317. p_command_name = p_name;
  318. }
  319. Ref<Shortcut> shortcut = ED_SHORTCUT(p_path, p_name, p_keycode);
  320. EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);
  321. return shortcut;
  322. }
  323. Ref<Shortcut> ED_SHORTCUT_ARRAY_AND_COMMAND(const String &p_path, const String &p_name, const PackedInt32Array &p_keycodes, String p_command_name) {
  324. if (p_command_name.is_empty()) {
  325. p_command_name = p_name;
  326. }
  327. Ref<Shortcut> shortcut = ED_SHORTCUT_ARRAY(p_path, p_name, p_keycodes);
  328. EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);
  329. return shortcut;
  330. }