fyrox_ui/menu.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
//! [`Menu`] and [`MenuItem`] widgets are used to create menu chains like standard `File`, `Edit`, etc. menus. See doc
//! of respective widget for more info and usage examples.
#![warn(missing_docs)]
use crate::{
border::BorderBuilder,
brush::Brush,
core::{
algebra::Vector2, color::Color, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
uuid_provider, variable::InheritableVariable, visitor::prelude::*,
},
decorator::{DecoratorBuilder, DecoratorMessage},
define_constructor,
draw::DrawingContext,
grid::{Column, GridBuilder, Row},
message::{ButtonState, KeyCode, MessageDirection, OsEvent, UiMessage},
popup::{Placement, Popup, PopupBuilder, PopupMessage},
stack_panel::StackPanelBuilder,
text::TextBuilder,
utils::{make_arrow_primitives, ArrowDirection},
vector_image::VectorImageBuilder,
widget::{Widget, WidgetBuilder, WidgetMessage},
BuildContext, Control, HorizontalAlignment, Orientation, RestrictionEntry, Thickness, UiNode,
UserInterface, VerticalAlignment, BRUSH_BRIGHT, BRUSH_BRIGHT_BLUE, BRUSH_PRIMARY,
};
use fyrox_graph::{BaseSceneGraph, SceneGraph, SceneGraphNode};
use std::any::TypeId;
use std::{
ops::{Deref, DerefMut},
sync::mpsc::Sender,
};
/// A set of messages that can be used to manipulate a [`Menu`] widget at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuMessage {
/// Activates the menu so it captures mouse input by itself and allows you to open menu item by a simple mouse
/// hover.
Activate,
/// Deactivates the menu.
Deactivate,
}
impl MenuMessage {
define_constructor!(
/// Creates [`MenuMessage::Activate`] message.
MenuMessage:Activate => fn activate(), layout: false
);
define_constructor!(
/// Creates [`MenuMessage::Deactivate`] message.
MenuMessage:Deactivate => fn deactivate(), layout: false
);
}
/// A set of messages that can be used to manipulate a [`MenuItem`] widget at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuItemMessage {
/// Opens the menu item's popup with inner items.
Open,
/// Closes the menu item's popup with inner items.
Close {
/// Defines, whether the item should be deselected when closed or not.
deselect: bool,
},
/// The message is generated by a menu item when it is clicked.
Click,
/// Adds a new item to the menu item.
AddItem(Handle<UiNode>),
/// Removes an item from the menu item.
RemoveItem(Handle<UiNode>),
/// Sets the new items of the menu item.
Items(Vec<Handle<UiNode>>),
/// Selects/deselects the item.
Select(bool),
}
impl MenuItemMessage {
define_constructor!(
/// Creates [`MenuItemMessage::Open`] message.
MenuItemMessage:Open => fn open(), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::Close`] message.
MenuItemMessage:Close => fn close(deselect: bool), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::Click`] message.
MenuItemMessage:Click => fn click(), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::AddItem`] message.
MenuItemMessage:AddItem => fn add_item(Handle<UiNode>), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::RemoveItem`] message.
MenuItemMessage:RemoveItem => fn remove_item(Handle<UiNode>), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::Items`] message.
MenuItemMessage:Items => fn items(Vec<Handle<UiNode>>), layout: false
);
define_constructor!(
/// Creates [`MenuItemMessage::Select`] message.
MenuItemMessage:Select => fn select(bool), layout: false
);
}
/// Menu widget is a root widget of an arbitrary menu hierarchy. An example could be "standard" menu strip with `File`, `Edit`, `View`, etc.
/// items. Menu widget can contain any number of children item (`File`, `Edit` in the previous example). These items should be [`MenuItem`]
/// widgets, however you can use any widget type (for example - to create some sort of a separator).
///
/// ## Examples
///
/// The next example creates a menu with the following structure:
///
/// ```text
/// | File | Edit |
/// |--Save |--Undo
/// |--Load |--Redo
/// ```
///
/// ```rust
/// # use fyrox_ui::{
/// # core::pool::Handle,
/// # menu::{MenuBuilder, MenuItemBuilder, MenuItemContent},
/// # widget::WidgetBuilder,
/// # BuildContext, UiNode,
/// # };
/// #
/// fn create_menu(ctx: &mut BuildContext) -> Handle<UiNode> {
/// MenuBuilder::new(WidgetBuilder::new())
/// .with_items(vec![
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("File"))
/// .with_items(vec![
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("Save"))
/// .build(ctx),
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("Load"))
/// .build(ctx),
/// ])
/// .build(ctx),
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("Edit"))
/// .with_items(vec![
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("Undo"))
/// .build(ctx),
/// MenuItemBuilder::new(WidgetBuilder::new())
/// .with_content(MenuItemContent::text_no_arrow("Redo"))
/// .build(ctx),
/// ])
/// .build(ctx),
/// ])
/// .build(ctx)
/// }
/// ```
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
pub struct Menu {
widget: Widget,
active: bool,
#[component(include)]
items: ItemsContainer,
}
crate::define_widget_deref!(Menu);
uuid_provider!(Menu = "582a04f3-a7fd-4e70-bbd1-eb95e2275b75");
impl Control for Menu {
fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
self.widget.handle_routed_message(ui, message);
if let Some(msg) = message.data::<MenuMessage>() {
match msg {
MenuMessage::Activate => {
if !self.active {
ui.push_picking_restriction(RestrictionEntry {
handle: self.handle(),
stop: false,
});
self.active = true;
}
}
MenuMessage::Deactivate => {
if self.active {
self.active = false;
ui.remove_picking_restriction(self.handle());
// Close descendant menu items.
let mut stack = self.children().to_vec();
while let Some(handle) = stack.pop() {
let node = ui.node(handle);
if let Some(item) = node.cast::<MenuItem>() {
ui.send_message(MenuItemMessage::close(
handle,
MessageDirection::ToWidget,
true,
));
// We have to search in popup content too because menu shows its content
// in popup and content could be another menu item.
stack.push(*item.items_panel);
}
// Continue depth search.
stack.extend_from_slice(node.children());
}
}
}
}
} else if let Some(WidgetMessage::KeyDown(key_code)) = message.data() {
if !message.handled() {
if keyboard_navigation(ui, *key_code, self, self.handle) {
message.set_handled(true);
} else if *key_code == KeyCode::Escape {
ui.send_message(MenuMessage::deactivate(
self.handle,
MessageDirection::ToWidget,
));
message.set_handled(true);
}
}
}
}
fn handle_os_event(
&mut self,
_self_handle: Handle<UiNode>,
ui: &mut UserInterface,
event: &OsEvent,
) {
// Handle menu items close by clicking outside of menu item. We using
// raw event here because we need to know the fact that mouse was clicked
// and we do not care which element was clicked so we'll get here in any
// case.
if let OsEvent::MouseInput { state, .. } = event {
if *state == ButtonState::Pressed && self.active {
// TODO: Make picking more accurate - right now it works only with rects.
let pos = ui.cursor_position();
if !self.widget.screen_bounds().contains(pos) {
// Also check if we clicked inside some descendant menu item - in this
// case we don't need to close menu.
let mut any_picked = false;
let mut stack = self.children().to_vec();
'depth_search: while let Some(handle) = stack.pop() {
let node = ui.node(handle);
if let Some(item) = node.cast::<MenuItem>() {
let popup = ui.node(*item.items_panel);
if popup.screen_bounds().contains(pos) && popup.is_globally_visible() {
// Once we found that we clicked inside some descendant menu item
// we can immediately stop search - we don't want to close menu
// items popups in this case and can safely skip all stuff below.
any_picked = true;
break 'depth_search;
}
// We have to search in popup content too because menu shows its content
// in popup and content could be another menu item.
stack.push(*item.items_panel);
}
// Continue depth search.
stack.extend_from_slice(node.children());
}
if !any_picked {
ui.send_message(MenuMessage::deactivate(
self.handle(),
MessageDirection::ToWidget,
));
}
}
}
}
}
}
/// A set of possible placements of a popup with items of a menu item.
#[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Hash, Visit, Reflect, Default, Debug)]
pub enum MenuItemPlacement {
/// Bottom placement.
Bottom,
/// Right placement.
#[default]
Right,
}
#[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Hash, Visit, Reflect, Default, Debug)]
enum NavigationDirection {
#[default]
Horizontal,
Vertical,
}
#[derive(Default, Clone, Debug, Visit, Reflect, ComponentProvider)]
#[doc(hidden)]
pub struct ItemsContainer {
#[doc(hidden)]
pub items: InheritableVariable<Vec<Handle<UiNode>>>,
navigation_direction: NavigationDirection,
}
impl Deref for ItemsContainer {
type Target = Vec<Handle<UiNode>>;
fn deref(&self) -> &Self::Target {
self.items.deref()
}
}
impl DerefMut for ItemsContainer {
fn deref_mut(&mut self) -> &mut Self::Target {
self.items.deref_mut()
}
}
impl ItemsContainer {
fn selected_item_index(&self, ui: &UserInterface) -> Option<usize> {
for (index, item) in self.items.iter().enumerate() {
if let Some(item_ref) = ui.try_get_of_type::<MenuItem>(*item) {
if *item_ref.is_selected {
return Some(index);
}
}
}
None
}
fn next_item_to_select_in_dir(&self, ui: &UserInterface, dir: isize) -> Option<Handle<UiNode>> {
self.selected_item_index(ui)
.map(|i| i as isize)
.and_then(|mut index| {
// Do a full circle search.
let count = self.items.len() as isize;
for _ in 0..count {
index += dir;
if index < 0 {
index += count;
}
index %= count;
let handle = self.items.get(index as usize).cloned();
if let Some(item) = handle.and_then(|h| ui.try_get_of_type::<MenuItem>(h)) {
if item.enabled() {
return handle;
}
}
}
None
})
}
}
/// Menu item is a widget with arbitrary content, that has a "floating" panel (popup) for sub-items if the menu item. This was menu items can form
/// arbitrary hierarchies. See [`Menu`] docs for examples.
#[derive(Default, Clone, Debug, Visit, Reflect, ComponentProvider)]
pub struct MenuItem {
/// Base widget of the menu item.
pub widget: Widget,
/// Current items of the menu item
#[component(include)]
pub items_container: ItemsContainer,
/// A handle of a popup that holds the items of the menu item.
pub items_panel: InheritableVariable<Handle<UiNode>>,
/// A handle of a panel widget that arranges items of the menu item.
pub panel: InheritableVariable<Handle<UiNode>>,
/// Current placement of the menu item.
pub placement: InheritableVariable<MenuItemPlacement>,
/// A flag, that defines whether the menu item is clickable when it has sub-items or not.
pub clickable_when_not_empty: InheritableVariable<bool>,
/// A handle to the decorator of the item.
pub decorator: InheritableVariable<Handle<UiNode>>,
/// Is this item selected or not.
pub is_selected: InheritableVariable<bool>,
}
crate::define_widget_deref!(MenuItem);
impl MenuItem {
fn is_opened(&self, ui: &UserInterface) -> bool {
ui.try_get_of_type::<ContextMenu>(*self.items_panel)
.map_or(false, |items_panel| *items_panel.popup.is_open)
}
}
// MenuItem uses popup to show its content, popup can be top-most only if it is
// direct child of root canvas of UI. This fact adds some complications to search
// of parent menu - we can't just traverse the tree because popup is not a child
// of menu item, instead we trying to fetch handle to parent menu item from popup's
// user data and continue up-search until we find menu.
fn find_menu(from: Handle<UiNode>, ui: &UserInterface) -> Handle<UiNode> {
let mut handle = from;
while handle.is_some() {
if let Some((_, panel)) = ui.find_component_up::<ContextMenu>(handle) {
// Continue search from parent menu item of popup.
handle = panel.parent_menu_item;
} else {
// Maybe we have Menu as parent for MenuItem.
return ui.find_handle_up(handle, &mut |n| n.cast::<Menu>().is_some());
}
}
Default::default()
}
fn is_any_menu_item_contains_point(ui: &UserInterface, pt: Vector2<f32>) -> bool {
for (handle, menu) in ui
.nodes()
.pair_iter()
.filter_map(|(h, n)| n.query_component::<MenuItem>().map(|menu| (h, menu)))
{
if ui.find_component_up::<Menu>(handle).is_none()
&& menu.is_globally_visible()
&& menu.screen_bounds().contains(pt)
{
return true;
}
}
false
}
fn close_menu_chain(from: Handle<UiNode>, ui: &UserInterface) {
let mut handle = from;
while handle.is_some() {
let popup_handle = ui.find_handle_up(handle, &mut |n| n.has_component::<ContextMenu>());
if let Some(panel) = ui.try_get_of_type::<ContextMenu>(popup_handle) {
ui.send_message(PopupMessage::close(
popup_handle,
MessageDirection::ToWidget,
));
// Continue search from parent menu item of popup.
handle = panel.parent_menu_item;
} else {
// Prevent infinite loops.
break;
}
}
}
uuid_provider!(MenuItem = "72e002c6-6060-4583-b5b7-0c5500244fef");
impl Control for MenuItem {
fn on_remove(&self, sender: &Sender<UiMessage>) {
// Popup won't be deleted with the menu item, because it is not the child of the item.
// So we have to remove it manually.
sender
.send(WidgetMessage::remove(
*self.items_panel,
MessageDirection::ToWidget,
))
.unwrap();
}
fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
self.widget.handle_routed_message(ui, message);
if let Some(msg) = message.data::<WidgetMessage>() {
match msg {
WidgetMessage::MouseDown { .. } => {
let menu = find_menu(self.parent(), ui);
if menu.is_some() {
// Activate menu so it user will be able to open submenus by
// mouse hover.
ui.send_message(MenuMessage::activate(menu, MessageDirection::ToWidget));
ui.send_message(MenuItemMessage::open(
self.handle(),
MessageDirection::ToWidget,
));
}
}
WidgetMessage::MouseUp { .. } => {
if !message.handled() {
if self.items_container.is_empty() || *self.clickable_when_not_empty {
ui.send_message(MenuItemMessage::click(
self.handle(),
MessageDirection::ToWidget,
));
}
if self.items_container.is_empty() {
let menu = find_menu(self.parent(), ui);
if menu.is_some() {
// Deactivate menu if we have one.
ui.send_message(MenuMessage::deactivate(
menu,
MessageDirection::ToWidget,
));
} else {
// Or close menu chain if menu item is in "orphaned" state.
close_menu_chain(self.parent(), ui);
}
}
message.set_handled(true);
}
}
WidgetMessage::MouseEnter => {
// While parent menu active it is possible to open submenus
// by simple mouse hover.
let menu = find_menu(self.parent(), ui);
let open = if menu.is_some() {
if let Some(menu) = ui.node(menu).cast::<Menu>() {
menu.active
} else {
false
}
} else {
true
};
if open {
ui.send_message(MenuItemMessage::open(
self.handle(),
MessageDirection::ToWidget,
));
}
}
WidgetMessage::MouseLeave => {
if !self.is_opened(ui) {
ui.send_message(MenuItemMessage::select(
self.handle,
MessageDirection::ToWidget,
false,
));
}
}
WidgetMessage::KeyDown(key_code) => {
if !message.handled() && *self.is_selected && *key_code == KeyCode::Enter {
ui.send_message(MenuItemMessage::click(
self.handle,
MessageDirection::FromWidget,
));
let menu = find_menu(self.parent(), ui);
ui.send_message(MenuMessage::deactivate(menu, MessageDirection::ToWidget));
message.set_handled(true);
}
}
_ => {}
}
} else if let Some(msg) = message.data::<MenuItemMessage>() {
if message.destination() == self.handle
&& message.direction() == MessageDirection::ToWidget
{
match msg {
MenuItemMessage::Select(selected) => {
if *self.is_selected != *selected {
self.is_selected.set_value_and_mark_modified(*selected);
ui.send_message(DecoratorMessage::select(
*self.decorator,
MessageDirection::ToWidget,
*selected,
));
if *selected {
ui.send_message(WidgetMessage::focus(
self.handle,
MessageDirection::ToWidget,
));
}
}
}
MenuItemMessage::Open => {
if !self.items_container.is_empty() {
let placement = match *self.placement {
MenuItemPlacement::Bottom => Placement::LeftBottom(self.handle),
MenuItemPlacement::Right => Placement::RightTop(self.handle),
};
if !*self.is_selected {
ui.send_message(MenuItemMessage::select(
self.handle,
MessageDirection::ToWidget,
true,
));
}
// Open popup.
ui.send_message(PopupMessage::placement(
*self.items_panel,
MessageDirection::ToWidget,
placement,
));
ui.send_message(PopupMessage::open(
*self.items_panel,
MessageDirection::ToWidget,
));
}
}
MenuItemMessage::Close { deselect } => {
ui.send_message(PopupMessage::close(
*self.items_panel,
MessageDirection::ToWidget,
));
if *deselect && *self.is_selected {
ui.send_message(MenuItemMessage::select(
self.handle,
MessageDirection::ToWidget,
false,
));
}
// Recursively deselect everything in the sub-items container.
for &item in &*self.items_container.items {
ui.send_message(MenuItemMessage::close(
item,
MessageDirection::ToWidget,
true,
));
}
}
MenuItemMessage::Click => {}
MenuItemMessage::AddItem(item) => {
ui.send_message(WidgetMessage::link(
*item,
MessageDirection::ToWidget,
*self.panel,
));
self.items_container.push(*item);
}
MenuItemMessage::RemoveItem(item) => {
if let Some(position) =
self.items_container.iter().position(|i| *i == *item)
{
self.items_container.remove(position);
ui.send_message(WidgetMessage::remove(
*item,
MessageDirection::ToWidget,
));
}
}
MenuItemMessage::Items(items) => {
for ¤t_item in self.items_container.iter() {
ui.send_message(WidgetMessage::remove(
current_item,
MessageDirection::ToWidget,
));
}
for &item in items {
ui.send_message(WidgetMessage::link(
item,
MessageDirection::ToWidget,
*self.panel,
));
}
self.items_container
.items
.set_value_and_mark_modified(items.clone());
}
}
}
}
}
fn preview_message(&self, ui: &UserInterface, message: &mut UiMessage) {
// We need to check if some new menu item opened and then close other not in
// direct chain of menu items until to menu.
if message.destination() != self.handle() {
if let Some(MenuItemMessage::Open) = message.data::<MenuItemMessage>() {
let mut found = false;
let mut handle = message.destination();
while handle.is_some() {
if handle == self.handle() {
found = true;
break;
} else {
let node = ui.node(handle);
if let Some(panel) = node.component_ref::<ContextMenu>() {
// Once we found popup in chain, we must extract handle
// of parent menu item to continue search.
handle = panel.parent_menu_item;
} else {
handle = node.parent();
}
}
}
if !found {
ui.send_message(MenuItemMessage::close(
self.handle(),
MessageDirection::ToWidget,
true,
));
}
}
}
}
fn handle_os_event(
&mut self,
_self_handle: Handle<UiNode>,
ui: &mut UserInterface,
event: &OsEvent,
) {
// Allow closing "orphaned" menus by clicking outside of them.
if let OsEvent::MouseInput { state, .. } = event {
if *state == ButtonState::Pressed {
if let Some(panel) = ui.node(*self.items_panel).query_component::<ContextMenu>() {
if *panel.popup.is_open {
// Ensure that cursor is outside of any menus.
if !is_any_menu_item_contains_point(ui, ui.cursor_position())
&& find_menu(self.parent(), ui).is_none()
{
ui.send_message(PopupMessage::close(
*self.items_panel,
MessageDirection::ToWidget,
));
// Close all other popups.
close_menu_chain(self.parent(), ui);
}
}
}
}
}
}
}
/// Menu builder creates [`Menu`] widgets and adds them to the user interface.
pub struct MenuBuilder {
widget_builder: WidgetBuilder,
items: Vec<Handle<UiNode>>,
}
impl MenuBuilder {
/// Creates new builder instance.
pub fn new(widget_builder: WidgetBuilder) -> Self {
Self {
widget_builder,
items: Default::default(),
}
}
/// Sets the desired items of the menu.
pub fn with_items(mut self, items: Vec<Handle<UiNode>>) -> Self {
self.items = items;
self
}
/// Finishes menu building and adds them to the user interface.
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
for &item in self.items.iter() {
if let Some(item) = ctx[item].cast_mut::<MenuItem>() {
item.placement
.set_value_and_mark_modified(MenuItemPlacement::Bottom);
}
}
let back = BorderBuilder::new(
WidgetBuilder::new()
.with_background(BRUSH_PRIMARY)
.with_child(
StackPanelBuilder::new(
WidgetBuilder::new().with_children(self.items.iter().cloned()),
)
.with_orientation(Orientation::Horizontal)
.build(ctx),
),
)
.build(ctx);
let menu = Menu {
widget: self
.widget_builder
.with_handle_os_events(true)
.with_child(back)
.build(),
active: false,
items: ItemsContainer {
items: self.items.into(),
navigation_direction: NavigationDirection::Horizontal,
},
};
ctx.add_node(UiNode::new(menu))
}
}
/// Allows you to set a content of a menu item either from a pre-built "layout" with icon/text/shortcut/arrow or a custom
/// widget.
pub enum MenuItemContent<'a, 'b> {
/// Quick-n-dirty way of building elements. It can cover most of use cases - it builds classic menu item:
///
/// ```text
/// _________________________
/// | | | | |
/// |icon| text |shortcut| > |
/// |____|______|________|___|
/// ```
Text {
/// Text of the menu item.
text: &'a str,
/// Shortcut of the menu item.
shortcut: &'b str,
/// Icon of the menu item. Usually it is a [`crate::image::Image`] or [`crate::vector_image::VectorImage`] widget instance.
icon: Handle<UiNode>,
/// Create an arrow or not.
arrow: bool,
},
/// Horizontally and Vertically centered text
///
/// ```text
/// _________________________
/// | |
/// | text |
/// |________________________|
/// ```
TextCentered(&'a str),
/// Allows to put any node into menu item. It allows to customize menu item how needed - i.e. put image in it, or other user
/// control.
Node(Handle<UiNode>),
}
impl<'a, 'b> MenuItemContent<'a, 'b> {
/// Creates a menu item content with a text, a shortcut and an arrow (with no icon).
pub fn text_with_shortcut(text: &'a str, shortcut: &'b str) -> Self {
MenuItemContent::Text {
text,
shortcut,
icon: Default::default(),
arrow: true,
}
}
/// Creates a menu item content with a text and an arrow (with no icon or shortcut).
pub fn text(text: &'a str) -> Self {
MenuItemContent::Text {
text,
shortcut: "",
icon: Default::default(),
arrow: true,
}
}
/// Creates a menu item content with a text only (with no icon, shortcut, arrow).
pub fn text_no_arrow(text: &'a str) -> Self {
MenuItemContent::Text {
text,
shortcut: "",
icon: Default::default(),
arrow: false,
}
}
/// Creates a menu item content with only horizontally and vertically centered text.
pub fn text_centered(text: &'a str) -> Self {
MenuItemContent::TextCentered(text)
}
}
/// Menu builder creates [`MenuItem`] widgets and adds them to the user interface.
pub struct MenuItemBuilder<'a, 'b> {
widget_builder: WidgetBuilder,
items: Vec<Handle<UiNode>>,
content: Option<MenuItemContent<'a, 'b>>,
back: Option<Handle<UiNode>>,
clickable_when_not_empty: bool,
}
impl<'a, 'b> MenuItemBuilder<'a, 'b> {
/// Creates new menu item builder instance.
pub fn new(widget_builder: WidgetBuilder) -> Self {
Self {
widget_builder,
items: Default::default(),
content: None,
back: None,
clickable_when_not_empty: false,
}
}
/// Sets the desired content of the menu item. In most cases [`MenuItemContent::text_no_arrow`] is enough here.
pub fn with_content(mut self, content: MenuItemContent<'a, 'b>) -> Self {
self.content = Some(content);
self
}
/// Sets the desired items of the menu.
pub fn with_items(mut self, items: Vec<Handle<UiNode>>) -> Self {
self.items = items;
self
}
/// Allows you to specify the background content. Background node is only for decoration purpose, it can be any kind of node,
/// by default it is Decorator.
pub fn with_back(mut self, handle: Handle<UiNode>) -> Self {
self.back = Some(handle);
self
}
/// Sets whether the menu item is clickable when it has sub-items or not.
pub fn with_clickable_when_not_empty(mut self, value: bool) -> Self {
self.clickable_when_not_empty = value;
self
}
/// Finishes menu item building and adds it to the user interface.
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
let content = match self.content {
None => Handle::NONE,
Some(MenuItemContent::Text {
text,
shortcut,
icon,
arrow,
}) => GridBuilder::new(
WidgetBuilder::new()
.with_child(icon)
.with_child(
TextBuilder::new(
WidgetBuilder::new()
.with_margin(Thickness::left(2.0))
.on_row(1)
.on_column(1),
)
.with_text(text)
.build(ctx),
)
.with_child(
TextBuilder::new(
WidgetBuilder::new()
.with_horizontal_alignment(HorizontalAlignment::Right)
.with_margin(Thickness::uniform(1.0))
.on_row(1)
.on_column(2),
)
.with_text(shortcut)
.build(ctx),
)
.with_child(if arrow {
VectorImageBuilder::new(
WidgetBuilder::new()
.with_visibility(!self.items.is_empty())
.on_row(1)
.on_column(3)
.with_foreground(BRUSH_BRIGHT)
.with_horizontal_alignment(HorizontalAlignment::Center)
.with_vertical_alignment(VerticalAlignment::Center),
)
.with_primitives(make_arrow_primitives(ArrowDirection::Right, 8.0))
.build(ctx)
} else {
Handle::NONE
}),
)
.add_row(Row::stretch())
.add_row(Row::auto())
.add_row(Row::stretch())
.add_column(Column::auto())
.add_column(Column::stretch())
.add_column(Column::auto())
.add_column(Column::strict(10.0))
.add_column(Column::strict(5.0))
.build(ctx),
Some(MenuItemContent::TextCentered(text)) => {
TextBuilder::new(WidgetBuilder::new().with_margin(Thickness::left_right(5.0)))
.with_text(text)
.with_horizontal_text_alignment(HorizontalAlignment::Center)
.with_vertical_text_alignment(VerticalAlignment::Center)
.build(ctx)
}
Some(MenuItemContent::Node(node)) => node,
};
let decorator = self.back.unwrap_or_else(|| {
DecoratorBuilder::new(
BorderBuilder::new(WidgetBuilder::new())
.with_stroke_thickness(Thickness::uniform(0.0)),
)
.with_hover_brush(BRUSH_BRIGHT_BLUE)
.with_selected_brush(BRUSH_BRIGHT_BLUE)
.with_normal_brush(BRUSH_PRIMARY)
.with_pressed_brush(Brush::Solid(Color::TRANSPARENT))
.with_pressable(false)
.build(ctx)
});
if content.is_some() {
ctx.link(content, decorator);
}
let panel;
let items_panel = ContextMenuBuilder::new(
PopupBuilder::new(WidgetBuilder::new().with_min_size(Vector2::new(10.0, 10.0)))
.with_content({
panel = StackPanelBuilder::new(
WidgetBuilder::new().with_children(self.items.iter().cloned()),
)
.build(ctx);
panel
})
// We'll manually control if popup is either open or closed.
.stays_open(true),
)
.build(ctx);
let menu = MenuItem {
widget: self
.widget_builder
.with_handle_os_events(true)
.with_preview_messages(true)
.with_child(decorator)
.build(),
items_panel: items_panel.into(),
items_container: ItemsContainer {
items: self.items.into(),
navigation_direction: NavigationDirection::Vertical,
},
placement: MenuItemPlacement::Right.into(),
panel: panel.into(),
clickable_when_not_empty: false.into(),
decorator: decorator.into(),
is_selected: Default::default(),
};
let handle = ctx.add_node(UiNode::new(menu));
// "Link" popup with its parent menu item.
if let Some(popup) = ctx[items_panel].cast_mut::<ContextMenu>() {
popup.parent_menu_item = handle;
}
handle
}
}
/// A simple wrapper over [`Popup`] widget, that holds the sub-items of a menu item and provides
/// an ability for keyboard navigation.
#[derive(Default, Clone, Debug, Visit, Reflect, TypeUuidProvider, ComponentProvider)]
#[type_uuid(id = "ad8e9e76-c213-4232-9bab-80ebcabd69fa")]
pub struct ContextMenu {
/// Inner popup widget of the context menu.
#[component(include)]
pub popup: Popup,
/// Parent menu item of the context menu. Allows you to build chained context menus.
pub parent_menu_item: Handle<UiNode>,
}
impl Deref for ContextMenu {
type Target = Widget;
fn deref(&self) -> &Self::Target {
&self.popup.widget
}
}
impl DerefMut for ContextMenu {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.popup.widget
}
}
impl Control for ContextMenu {
fn on_remove(&self, sender: &Sender<UiMessage>) {
self.popup.on_remove(sender)
}
fn measure_override(&self, ui: &UserInterface, available_size: Vector2<f32>) -> Vector2<f32> {
self.popup.measure_override(ui, available_size)
}
fn arrange_override(&self, ui: &UserInterface, final_size: Vector2<f32>) -> Vector2<f32> {
self.popup.arrange_override(ui, final_size)
}
fn draw(&self, drawing_context: &mut DrawingContext) {
self.popup.draw(drawing_context)
}
fn post_draw(&self, drawing_context: &mut DrawingContext) {
self.popup.post_draw(drawing_context)
}
fn update(&mut self, dt: f32, ui: &mut UserInterface) {
self.popup.update(dt, ui);
}
fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
self.popup.handle_routed_message(ui, message);
if let Some(WidgetMessage::KeyDown(key_code)) = message.data() {
if !message.handled() {
if let Some(parent_menu_item) = ui.try_get(self.parent_menu_item) {
if keyboard_navigation(
ui,
*key_code,
parent_menu_item.deref(),
self.parent_menu_item,
) {
message.set_handled(true);
}
}
}
}
}
fn preview_message(&self, ui: &UserInterface, message: &mut UiMessage) {
self.popup.preview_message(ui, message)
}
fn handle_os_event(
&mut self,
self_handle: Handle<UiNode>,
ui: &mut UserInterface,
event: &OsEvent,
) {
self.popup.handle_os_event(self_handle, ui, event)
}
}
/// Creates [`ContextMenu`] widgets.
pub struct ContextMenuBuilder {
popup_builder: PopupBuilder,
parent_menu_item: Handle<UiNode>,
}
impl ContextMenuBuilder {
/// Creates new builder instance using an instance of the [`PopupBuilder`].
pub fn new(popup_builder: PopupBuilder) -> Self {
Self {
popup_builder,
parent_menu_item: Default::default(),
}
}
/// Sets the desired parent menu item.
pub fn with_parent_menu_item(mut self, parent_menu_item: Handle<UiNode>) -> Self {
self.parent_menu_item = parent_menu_item;
self
}
/// Finishes context menu building.
pub fn build_context_menu(self, ctx: &mut BuildContext) -> ContextMenu {
ContextMenu {
popup: self.popup_builder.build_popup(ctx),
parent_menu_item: self.parent_menu_item,
}
}
/// Finishes context menu building and adds it to the user interface.
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
let context_menu = self.build_context_menu(ctx);
ctx.add_node(UiNode::new(context_menu))
}
}
fn keyboard_navigation(
ui: &UserInterface,
key_code: KeyCode,
parent_menu_item: &dyn Control,
parent_menu_item_handle: Handle<UiNode>,
) -> bool {
let Some(items_container) = parent_menu_item
.query_component_ref(TypeId::of::<ItemsContainer>())
.and_then(|c| c.downcast_ref::<ItemsContainer>())
else {
return false;
};
let (close_key, enter_key, next_key, prev_key) = match items_container.navigation_direction {
NavigationDirection::Horizontal => (
KeyCode::ArrowUp,
KeyCode::ArrowDown,
KeyCode::ArrowRight,
KeyCode::ArrowLeft,
),
NavigationDirection::Vertical => (
KeyCode::ArrowLeft,
KeyCode::ArrowRight,
KeyCode::ArrowDown,
KeyCode::ArrowUp,
),
};
if key_code == close_key {
ui.send_message(MenuItemMessage::close(
parent_menu_item_handle,
MessageDirection::ToWidget,
false,
));
return true;
} else if key_code == enter_key {
if let Some(selected_item_index) = items_container.selected_item_index(ui) {
let selected_item = items_container.items[selected_item_index];
ui.send_message(MenuItemMessage::open(
selected_item,
MessageDirection::ToWidget,
));
if let Some(selected_item_ref) = ui.try_get_of_type::<MenuItem>(selected_item) {
if let Some(first_item) = selected_item_ref.items_container.first() {
ui.send_message(MenuItemMessage::select(
*first_item,
MessageDirection::ToWidget,
true,
));
}
}
}
return true;
} else if key_code == next_key || key_code == prev_key {
if let Some(selected_item_index) = items_container.selected_item_index(ui) {
let dir = if key_code == next_key {
1
} else if key_code == prev_key {
-1
} else {
unreachable!()
};
if let Some(new_selection) = items_container.next_item_to_select_in_dir(ui, dir) {
ui.send_message(MenuItemMessage::select(
items_container.items[selected_item_index],
MessageDirection::ToWidget,
false,
));
ui.send_message(MenuItemMessage::select(
new_selection,
MessageDirection::ToWidget,
true,
));
return true;
}
} else if let Some(first_item) = items_container.items.first() {
ui.send_message(MenuItemMessage::select(
*first_item,
MessageDirection::ToWidget,
true,
));
return true;
}
}
false
}