editor_command_palette.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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(SceneStringName(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_event) {
  156. // Redirect navigational key events to the tree.
  157. Ref<InputEventKey> key = p_event;
  158. if (key.is_valid()) {
  159. 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")) {
  160. search_options->gui_input(key);
  161. command_search_box->accept_event();
  162. }
  163. }
  164. }
  165. void EditorCommandPalette::_confirmed() {
  166. TreeItem *selected_option = search_options->get_selected();
  167. const String command_key = selected_option != nullptr ? selected_option->get_metadata(0) : "";
  168. if (!command_key.is_empty()) {
  169. hide();
  170. callable_mp(this, &EditorCommandPalette::execute_command).call_deferred(command_key);
  171. }
  172. }
  173. void EditorCommandPalette::open_popup() {
  174. if (was_showed) {
  175. popup(prev_rect);
  176. } else {
  177. popup_centered_clamped(Size2(600, 440) * EDSCALE, 0.8f);
  178. }
  179. command_search_box->clear();
  180. command_search_box->grab_focus();
  181. search_options->scroll_to_item(search_options->get_root());
  182. }
  183. void EditorCommandPalette::get_actions_list(List<String> *p_list) const {
  184. for (const KeyValue<String, Command> &E : commands) {
  185. p_list->push_back(E.key);
  186. }
  187. }
  188. void EditorCommandPalette::remove_command(String p_key_name) {
  189. ERR_FAIL_COND_MSG(!commands.has(p_key_name), "The Command '" + String(p_key_name) + "' doesn't exists. Unable to remove it.");
  190. commands.erase(p_key_name);
  191. }
  192. void EditorCommandPalette::add_command(String p_command_name, String p_key_name, Callable p_action, Vector<Variant> arguments, const Ref<Shortcut> &p_shortcut) {
  193. ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
  194. const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * arguments.size());
  195. for (int i = 0; i < arguments.size(); i++) {
  196. argptrs[i] = &arguments[i];
  197. }
  198. Command command;
  199. command.name = p_command_name;
  200. command.callable = p_action.bindp(argptrs, arguments.size());
  201. if (p_shortcut.is_null()) {
  202. command.shortcut_text = "None";
  203. } else {
  204. command.shortcut = p_shortcut;
  205. command.shortcut_text = p_shortcut->get_as_text();
  206. }
  207. commands[p_key_name] = command;
  208. }
  209. void EditorCommandPalette::_add_command(String p_command_name, String p_key_name, Callable p_binded_action, String p_shortcut_text) {
  210. ERR_FAIL_COND_MSG(commands.has(p_key_name), "The Command '" + String(p_command_name) + "' already exists. Unable to add it.");
  211. Command command;
  212. command.name = p_command_name;
  213. command.callable = p_binded_action;
  214. command.shortcut_text = p_shortcut_text;
  215. // 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.
  216. Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
  217. if (command_history.has(p_key_name)) {
  218. command.last_used = command_history[p_key_name];
  219. }
  220. commands[p_key_name] = command;
  221. }
  222. void EditorCommandPalette::execute_command(const String &p_command_key) {
  223. ERR_FAIL_COND_MSG(!commands.has(p_command_key), p_command_key + " not found.");
  224. commands[p_command_key].last_used = OS::get_singleton()->get_unix_time();
  225. _save_history();
  226. Variant ret;
  227. Callable::CallError ce;
  228. const Callable &callable = commands[p_command_key].callable;
  229. callable.callp(nullptr, 0, ret, ce);
  230. if (ce.error != Callable::CallError::CALL_OK) {
  231. 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);
  232. }
  233. }
  234. void EditorCommandPalette::register_shortcuts_as_command() {
  235. for (const KeyValue<String, Pair<String, Ref<Shortcut>>> &E : unregistered_shortcuts) {
  236. String command_name = E.value.first;
  237. Ref<Shortcut> shortcut = E.value.second;
  238. Ref<InputEventShortcut> ev;
  239. ev.instantiate();
  240. ev->set_shortcut(shortcut);
  241. add_command(command_name, E.key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), shortcut);
  242. }
  243. unregistered_shortcuts.clear();
  244. // Load command use history.
  245. Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
  246. Array history_entries = command_history.keys();
  247. for (int i = 0; i < history_entries.size(); i++) {
  248. const String &history_key = history_entries[i];
  249. if (commands.has(history_key)) {
  250. commands[history_key].last_used = command_history[history_key];
  251. }
  252. }
  253. }
  254. Ref<Shortcut> EditorCommandPalette::add_shortcut_command(const String &p_command, const String &p_key, Ref<Shortcut> p_shortcut) {
  255. if (is_inside_tree()) {
  256. Ref<InputEventShortcut> ev;
  257. ev.instantiate();
  258. ev->set_shortcut(p_shortcut);
  259. add_command(p_command, p_key, callable_mp(EditorNode::get_singleton()->get_viewport(), &Viewport::push_input), varray(ev, false), p_shortcut);
  260. } else {
  261. const String key_name = String(p_key);
  262. const String command_name = String(p_command);
  263. Pair pair = Pair(command_name, p_shortcut);
  264. unregistered_shortcuts[key_name] = pair;
  265. }
  266. return p_shortcut;
  267. }
  268. void EditorCommandPalette::_save_history() const {
  269. Dictionary command_history;
  270. for (const KeyValue<String, Command> &E : commands) {
  271. if (E.value.last_used > 0) {
  272. command_history[E.key] = E.value.last_used;
  273. }
  274. }
  275. EditorSettings::get_singleton()->set_project_metadata("command_palette", "command_history", command_history);
  276. }
  277. EditorCommandPalette *EditorCommandPalette::get_singleton() {
  278. if (singleton == nullptr) {
  279. singleton = memnew(EditorCommandPalette);
  280. }
  281. return singleton;
  282. }
  283. EditorCommandPalette::EditorCommandPalette() {
  284. set_hide_on_ok(false);
  285. connect(SceneStringName(confirmed), callable_mp(this, &EditorCommandPalette::_confirmed));
  286. VBoxContainer *vbc = memnew(VBoxContainer);
  287. add_child(vbc);
  288. command_search_box = memnew(LineEdit);
  289. command_search_box->set_placeholder(TTR("Filter Commands"));
  290. command_search_box->connect(SceneStringName(gui_input), callable_mp(this, &EditorCommandPalette::_sbox_input));
  291. command_search_box->connect(SceneStringName(text_changed), callable_mp(this, &EditorCommandPalette::_update_command_search));
  292. command_search_box->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  293. command_search_box->set_clear_button_enabled(true);
  294. MarginContainer *margin_container_csb = memnew(MarginContainer);
  295. margin_container_csb->add_child(command_search_box);
  296. vbc->add_child(margin_container_csb);
  297. register_text_enter(command_search_box);
  298. search_options = memnew(Tree);
  299. search_options->connect("item_activated", callable_mp(this, &EditorCommandPalette::_confirmed));
  300. search_options->connect(SceneStringName(item_selected), callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(false));
  301. search_options->connect("nothing_selected", callable_mp((BaseButton *)get_ok_button(), &BaseButton::set_disabled).bind(true));
  302. search_options->create_item();
  303. search_options->set_hide_root(true);
  304. search_options->set_columns(2);
  305. search_options->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  306. search_options->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  307. search_options->set_column_custom_minimum_width(0, int(8 * EDSCALE));
  308. vbc->add_child(search_options, true);
  309. }
  310. Ref<Shortcut> ED_SHORTCUT_AND_COMMAND(const String &p_path, const String &p_name, Key p_keycode, String p_command_name) {
  311. if (p_command_name.is_empty()) {
  312. p_command_name = p_name;
  313. }
  314. Ref<Shortcut> shortcut = ED_SHORTCUT(p_path, p_name, p_keycode);
  315. EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);
  316. return shortcut;
  317. }
  318. Ref<Shortcut> ED_SHORTCUT_ARRAY_AND_COMMAND(const String &p_path, const String &p_name, const PackedInt32Array &p_keycodes, String p_command_name) {
  319. if (p_command_name.is_empty()) {
  320. p_command_name = p_name;
  321. }
  322. Ref<Shortcut> shortcut = ED_SHORTCUT_ARRAY(p_path, p_name, p_keycodes);
  323. EditorCommandPalette::get_singleton()->add_shortcut_command(p_command_name, p_path, shortcut);
  324. return shortcut;
  325. }