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
//! Types used to construct a menu
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use dbus::arg::{RefArg, Variant};
// pub struct Properties {
// /// Tells if the menus are in a normal state or they believe that they
// /// could use some attention. Cases for showing them would be if help
// /// were referring to them or they accessors were being highlighted.
// /// This property can have two values: "normal" in almost all cases and
// /// "notice" when they should have a higher priority to be shown.
// pub status: Status,
// /// A list of directories that should be used for finding icons using
// /// the icon naming spec. Idealy there should only be one for the icon
// /// theme, but additional ones are often added by applications for
// /// app specific icons.
// pub icon_theme_path: Vec<String>,
// }
/// Direction of texts
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TextDirection {
LeftToRight,
RightToLeft,
}
impl fmt::Display for TextDirection {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let r = match *self {
TextDirection::LeftToRight => "ltr",
TextDirection::RightToLeft => "rtl",
};
f.write_str(r)
}
}
pub(crate) enum Status {
Normal,
Notice,
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let r = match *self {
Status::Normal => "normal",
Status::Notice => "notice",
};
f.write_str(r)
}
}
/// All types of menu item
///
/// Do not use directly (except [`MenuItem::Separator`]), see examples in top level documents
pub enum MenuItem<T> {
Standard(StandardItem<T>),
/// A separator
Separator,
Checkmark(CheckmarkItem<T>),
SubMenu(SubMenu<T>),
RadioGroup(RadioGroup<T>),
}
/// Menu item, the standard one
pub struct StandardItem<T> {
/// Text of the item, except that:
/// -# two consecutive underscore characters "__" are displayed as a
/// single underscore,
/// -# any remaining underscore characters are not displayed at all,
/// -# the first of those remaining underscore characters (unless it is
/// the last character in the string) indicates that the following
/// character is the access key.
pub label: String,
/// Whether the item can be activated or not.
pub enabled: bool,
/// True if the item is visible in the menu.
pub visible: bool,
/// Icon name of the item, following the freedesktop.org icon spec.
pub icon_name: String,
/// PNG data of the icon.
pub icon_data: Vec<u8>,
/// The shortcut of the item. Each array represents the key press
/// in the list of keypresses. Each list of strings contains a list of
/// modifiers and then the key that is used. The modifier strings
/// allowed are: "Control", "Alt", "Shift" and "Super".
/// - A simple shortcut like Ctrl+S is represented as:
/// [["Control", "S"]]
/// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
/// [["Control", "Q"], ["Alt", "X"]]
pub shortcut: Vec<Vec<String>>,
/// How the menuitem feels the information it's displaying to the
/// user should be presented.
pub disposition: Disposition,
pub activate: Box<dyn Fn(&mut T)>,
}
impl<T> Default for StandardItem<T> {
fn default() -> Self {
StandardItem {
label: String::default(),
enabled: true,
visible: true,
icon_name: String::default(),
icon_data: Vec::default(),
shortcut: Vec::default(),
disposition: Disposition::Normal,
activate: Box::new(|_this| {}),
}
}
}
impl<T> From<StandardItem<T>> for MenuItem<T> {
fn from(item: StandardItem<T>) -> Self {
MenuItem::Standard(item)
}
}
impl<T: 'static> From<StandardItem<T>> for RawMenuItem<T> {
fn from(item: StandardItem<T>) -> Self {
let activate = item.activate;
Self {
r#type: ItemType::Standard,
label: item.label,
enabled: item.enabled,
visible: item.visible,
icon_name: item.icon_name,
icon_data: item.icon_data,
shortcut: item.shortcut,
disposition: item.disposition,
on_clicked: Rc::new(move |this, _id| {
(activate)(this);
}),
..Default::default()
}
}
}
/// Menu item, a container of another menu tree
pub struct SubMenu<T> {
/// Text of the item, except that:
/// -# two consecutive underscore characters "__" are displayed as a
/// single underscore,
/// -# any remaining underscore characters are not displayed at all,
/// -# the first of those remaining underscore characters (unless it is
/// the last character in the string) indicates that the following
/// character is the access key.
pub label: String,
/// Whether the item can be activated or not.
pub enabled: bool,
/// True if the item is visible in the menu.
pub visible: bool,
/// Icon name of the item, following the freedesktop.org icon spec.
pub icon_name: String,
/// PNG data of the icon.
pub icon_data: Vec<u8>,
/// The shortcut of the item. Each array represents the key press
/// in the list of keypresses. Each list of strings contains a list of
/// modifiers and then the key that is used. The modifier strings
/// allowed are: "Control", "Alt", "Shift" and "Super".
/// - A simple shortcut like Ctrl+S is represented as:
/// [["Control", "S"]]
/// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
/// [["Control", "Q"], ["Alt", "X"]]
pub shortcut: Vec<Vec<String>>,
/// How the menuitem feels the information it's displaying to the
/// user should be presented.
pub disposition: Disposition,
pub submenu: Vec<MenuItem<T>>,
}
impl<T> Default for SubMenu<T> {
fn default() -> Self {
Self {
label: String::default(),
enabled: true,
visible: true,
icon_name: String::default(),
icon_data: Vec::default(),
shortcut: Vec::default(),
disposition: Disposition::Normal,
submenu: Vec::default(),
}
}
}
impl<T> From<SubMenu<T>> for MenuItem<T> {
fn from(item: SubMenu<T>) -> Self {
MenuItem::SubMenu(item)
}
}
impl<T> From<SubMenu<T>> for RawMenuItem<T> {
fn from(item: SubMenu<T>) -> Self {
Self {
r#type: ItemType::Standard,
label: item.label,
enabled: item.enabled,
visible: item.visible,
icon_name: item.icon_name,
icon_data: item.icon_data,
shortcut: item.shortcut,
disposition: item.disposition,
on_clicked: Rc::new(move |_this, _id| Default::default()),
..Default::default()
}
}
}
/// Menu item, checkable
pub struct CheckmarkItem<T> {
/// Text of the item, except that:
/// -# two consecutive underscore characters "__" are displayed as a
/// single underscore,
/// -# any remaining underscore characters are not displayed at all,
/// -# the first of those remaining underscore characters (unless it is
/// the last character in the string) indicates that the following
/// character is the access key.
pub label: String,
/// Whether the item can be activated or not.
pub enabled: bool,
/// True if the item is visible in the menu.
pub visible: bool,
pub checked: bool,
/// PNG data of the icon.
pub icon_name: String,
/// PNG data of the icon.
pub icon_data: Vec<u8>,
/// The shortcut of the item. Each array represents the key press
/// in the list of keypresses. Each list of strings contains a list of
/// modifiers and then the key that is used. The modifier strings
/// allowed are: "Control", "Alt", "Shift" and "Super".
/// - A simple shortcut like Ctrl+S is represented as:
/// [["Control", "S"]]
/// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
/// [["Control", "Q"], ["Alt", "X"]]
pub shortcut: Vec<Vec<String>>,
/// How the menuitem feels the information it's displaying to the
/// user should be presented.
pub disposition: Disposition,
pub activate: Box<dyn Fn(&mut T)>,
}
impl<T> Default for CheckmarkItem<T> {
fn default() -> Self {
CheckmarkItem {
label: String::default(),
enabled: true,
visible: true,
checked: false,
icon_name: String::default(),
icon_data: Vec::default(),
shortcut: Vec::default(),
disposition: Disposition::Normal,
activate: Box::new(|_this| {}),
}
}
}
impl<T> From<CheckmarkItem<T>> for MenuItem<T> {
fn from(item: CheckmarkItem<T>) -> Self {
MenuItem::Checkmark(item)
}
}
impl<T: 'static> From<CheckmarkItem<T>> for RawMenuItem<T> {
fn from(item: CheckmarkItem<T>) -> Self {
let activate = item.activate;
Self {
r#type: ItemType::Standard,
label: item.label,
enabled: item.enabled,
visible: item.visible,
icon_name: item.icon_name,
icon_data: item.icon_data,
shortcut: item.shortcut,
toggle_type: ToggleType::Checkmark,
toggle_state: if item.checked {
ToggleState::On
} else {
ToggleState::Off
},
disposition: item.disposition,
on_clicked: Rc::new(move |this, _id| {
(activate)(this);
}),
..Default::default()
}
}
}
/// Menu item, contains [`RadioItem`]
pub struct RadioGroup<T> {
pub selected: usize,
pub select: Box<dyn Fn(&mut T, usize)>,
pub options: Vec<RadioItem>,
}
impl<T> Default for RadioGroup<T> {
fn default() -> Self {
Self {
selected: 0,
select: Box::new(|_, _| {}),
options: Default::default(),
}
}
}
impl<T> From<RadioGroup<T>> for MenuItem<T> {
fn from(item: RadioGroup<T>) -> Self {
MenuItem::RadioGroup(item)
}
}
/// Items of [`RadioGroup`]
pub struct RadioItem {
/// Text of the item, except that:
/// -# two consecutive underscore characters "__" are displayed as a
/// single underscore,
/// -# any remaining underscore characters are not displayed at all,
/// -# the first of those remaining underscore characters (unless it is
/// the last character in the string) indicates that the following
/// character is the access key.
pub label: String,
/// Whether the item can be activated or not.
pub enabled: bool,
/// True if the item is visible in the menu.
pub visible: bool,
/// Icon name of the item, following the freedesktop.org icon spec.
pub icon_name: String,
/// PNG data of the icon.
pub icon_data: Vec<u8>,
/// The shortcut of the item. Each array represents the key press
/// in the list of keypresses. Each list of strings contains a list of
/// modifiers and then the key that is used. The modifier strings
/// allowed are: "Control", "Alt", "Shift" and "Super".
/// - A simple shortcut like Ctrl+S is represented as:
/// [["Control", "S"]]
/// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
/// [["Control", "Q"], ["Alt", "X"]]
pub shortcut: Vec<Vec<String>>,
/// How the menuitem feels the information it's displaying to the
/// user should be presented.
pub disposition: Disposition,
}
impl Default for RadioItem {
fn default() -> Self {
Self {
label: String::default(),
enabled: true,
visible: true,
icon_name: String::default(),
icon_data: Vec::default(),
shortcut: Vec::default(),
disposition: Disposition::Normal,
}
}
}
pub(crate) struct RawMenuItem<T> {
r#type: ItemType,
/// Text of the item, except that:
/// -# two consecutive underscore characters "__" are displayed as a
/// single underscore,
/// -# any remaining underscore characters are not displayed at all,
/// -# the first of those remaining underscore characters (unless it is
/// the last character in the string) indicates that the following
/// character is the access key.
label: String,
/// Whether the item can be activated or not.
enabled: bool,
/// True if the item is visible in the menu.
visible: bool,
/// Icon name of the item, following the freedesktop.org icon spec.
icon_name: String,
/// PNG data of the icon.
icon_data: Vec<u8>,
/// The shortcut of the item. Each array represents the key press
/// in the list of keypresses. Each list of strings contains a list of
/// modifiers and then the key that is used. The modifier strings
/// allowed are: "Control", "Alt", "Shift" and "Super".
/// - A simple shortcut like Ctrl+S is represented as:
/// [["Control", "S"]]
/// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
/// [["Control", "Q"], ["Alt", "X"]]
shortcut: Vec<Vec<String>>,
toggle_type: ToggleType,
/// Describe the current state of a "togglable" item.
/// Note:
/// The implementation does not itself handle ensuring that only one
/// item in a radio group is set to "on", or that a group does not have
/// "on" and "indeterminate" items simultaneously; maintaining this
/// policy is up to the toolkit wrappers.
toggle_state: ToggleState,
/// How the menuitem feels the information it's displaying to the
/// user should be presented.
disposition: Disposition,
pub on_clicked: Rc<dyn Fn(&mut T, usize)>,
vendor_properties: HashMap<VendorSpecific, Variant<Box<dyn RefArg + 'static>>>,
}
impl<T> Clone for RawMenuItem<T> {
fn clone(&self) -> Self {
let vendor_properties = self
.vendor_properties
.iter()
.map(|(k, v)| (k.clone(), Variant(v.0.box_clone())))
.collect();
RawMenuItem {
r#type: self.r#type.clone(),
label: self.label.clone(),
enabled: self.enabled,
visible: self.visible,
icon_name: self.icon_name.clone(),
icon_data: self.icon_data.clone(),
shortcut: self.shortcut.clone(),
toggle_type: self.toggle_type,
toggle_state: self.toggle_state,
disposition: self.disposition,
on_clicked: self.on_clicked.clone(),
vendor_properties,
}
}
}
macro_rules! if_not_default_then_insert {
($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident) => {
if_not_default_then_insert!($map, $item, $default, $filter, $property, (|r| r));
};
($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident, $to_refarg: tt) => {{
let name = stringify!($property).replace('_', "-");
if_not_default_then_insert!($map, $item, $default, $filter, $property, name, $to_refarg);
}};
($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident, $property_name: tt, $to_refarg: tt) => {
if ($filter.is_empty() || $filter.contains(&&*$property_name))
&& $item.$property != $default.$property
{
$map.insert(
$property_name.to_string(),
Variant(Box::new($to_refarg($item.$property))),
);
}
};
}
impl<T> fmt::Debug for RawMenuItem<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Item {}", self.label)
}
}
impl<T> RawMenuItem<T> {
pub(crate) fn to_dbus_map(
&self,
filter: &[&str],
) -> HashMap<String, Variant<Box<dyn RefArg + 'static>>> {
let item = self.clone();
let mut properties: HashMap<String, Variant<Box<dyn RefArg + 'static>>> =
HashMap::with_capacity(11);
let default: RawMenuItem<T> = RawMenuItem::default();
if_not_default_then_insert!(
properties,
item,
default,
filter,
r#type,
"type",
(|r: ItemType| r.to_string())
);
if_not_default_then_insert!(properties, item, default, filter, label);
if_not_default_then_insert!(properties, item, default, filter, enabled);
if_not_default_then_insert!(properties, item, default, filter, visible);
if_not_default_then_insert!(properties, item, default, filter, icon_name);
if_not_default_then_insert!(properties, item, default, filter, icon_data);
if_not_default_then_insert!(properties, item, default, filter, shortcut);
if_not_default_then_insert!(
properties,
item,
default,
filter,
toggle_type,
(|r: ToggleType| r.to_string())
);
if_not_default_then_insert!(
properties,
item,
default,
filter,
toggle_state,
(|r| r as i32)
);
if_not_default_then_insert!(
properties,
item,
default,
filter,
disposition,
(|r: Disposition| r.to_string())
);
for (k, v) in item.vendor_properties {
properties.insert(k.to_string(), v);
}
properties
}
pub(crate) fn diff(
&self,
other: Self,
) -> Option<(HashMap<String, Variant<Box<dyn RefArg>>>, Vec<String>)> {
let default = Self::default();
let mut updated_props: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
let mut removed_props = Vec::new();
if self.r#type != other.r#type {
if other.r#type == default.r#type {
removed_props.push("type".into());
} else {
updated_props.insert("type".into(), Variant(Box::new(other.r#type.to_string())));
}
}
if self.label != other.label {
if other.label == default.label {
removed_props.push("label".into());
} else {
updated_props.insert("label".into(), Variant(Box::new(other.label)));
}
}
if self.enabled != other.enabled {
if other.enabled == default.enabled {
removed_props.push("enabled".into());
} else {
updated_props.insert("enabled".into(), Variant(Box::new(other.enabled)));
}
}
if self.visible != other.visible {
if other.visible == default.visible {
removed_props.push("visible".into());
} else {
updated_props.insert("visible".into(), Variant(Box::new(other.visible)));
}
}
if self.icon_name != other.icon_name {
if other.icon_name == default.icon_name {
removed_props.push("icon-name".into());
} else {
updated_props.insert("icon-name".into(), Variant(Box::new(other.icon_name)));
}
}
if self.icon_data != other.icon_data {
if other.icon_data == default.icon_data {
removed_props.push("icon-data".into());
} else {
updated_props.insert("icon-data".into(), Variant(Box::new(other.icon_data)));
}
}
if self.shortcut != other.shortcut {
if other.shortcut == default.shortcut {
removed_props.push("shortcut".into());
} else {
updated_props.insert("shortcut".into(), Variant(Box::new(other.shortcut)));
}
}
if self.toggle_type != other.toggle_type {
if other.toggle_type == default.toggle_type {
removed_props.push("toggle-type".into());
} else {
updated_props.insert(
"toggle-type".into(),
Variant(Box::new(other.toggle_type.to_string())),
);
}
}
if self.toggle_state != other.toggle_state {
if other.toggle_state == default.toggle_state {
removed_props.push("toggle-state".into());
} else {
updated_props.insert(
"toggle-state".into(),
Variant(Box::new(other.toggle_state as i32)),
);
}
}
if self.disposition != other.disposition {
if other.disposition == default.disposition {
removed_props.push("disposition".into());
} else {
updated_props.insert(
"disposition".into(),
Variant(Box::new(other.disposition.to_string())),
);
}
}
// TODO: vendor_properties
if updated_props.is_empty() && removed_props.is_empty() {
None
} else {
Some((updated_props, removed_props))
}
}
}
impl<T> Default for RawMenuItem<T> {
fn default() -> Self {
RawMenuItem {
r#type: ItemType::Standard,
label: String::default(),
enabled: true,
visible: true,
icon_name: String::default(),
icon_data: Vec::default(),
shortcut: Vec::default(),
toggle_type: ToggleType::Null,
toggle_state: ToggleState::Indeterminate,
disposition: Disposition::Normal,
//submenu: Vec::default(),
on_clicked: Rc::new(|_this, _id| Default::default()),
vendor_properties: HashMap::default(),
}
}
}
/// Vendor specific types/properties
/// will be formatted to "x-<vendor>-<name>""
#[doc(hidden)]
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct VendorSpecific {
pub vendor: String,
pub name: String,
}
impl fmt::Display for VendorSpecific {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "x-{}-{}", self.vendor, self.name)
}
}
#[allow(dead_code)]
#[derive(Debug, Eq, PartialEq, Clone)]
enum ItemType {
/// An item which can be clicked to trigger an action or show another menu
Standard,
/// A separator
Separator,
/// Vendor specific types
Vendor(VendorSpecific),
}
impl fmt::Display for ItemType {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use ItemType::*;
match self {
Standard => f.write_str("standard"),
Separator => f.write_str("separator"),
Vendor(vendor) => vendor.fmt(f),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum ToggleType {
/// Item is an independent togglable item
Checkmark,
/// Item is part of a group where only one item can be toggled at a time
Radio,
/// Item cannot be toggled
Null,
}
impl fmt::Display for ToggleType {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use ToggleType::*;
let r = match self {
Checkmark => "checkmark",
Radio => "radio",
Null => "",
};
f.write_str(r)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum ToggleState {
Off = 0,
On = 1,
Indeterminate = -1,
}
/// Item disposition
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Disposition {
/// A standard menu item
Normal,
/// Providing additional information to the user
Informative,
/// Looking at potentially harmful results
Warning,
/// Something bad could potentially happen
Alert,
}
impl fmt::Display for Disposition {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use Disposition::*;
let r = match self {
Normal => "normal",
Informative => "informative",
Warning => "warning",
Alert => "alert",
};
f.write_str(r)
}
}
pub(crate) fn menu_flatten<T: 'static>(
items: Vec<MenuItem<T>>,
) -> Vec<(RawMenuItem<T>, Vec<usize>)> {
let mut list: Vec<(RawMenuItem<T>, Vec<usize>)> =
vec![(RawMenuItem::default(), Vec::with_capacity(items.len()))];
let mut stack = vec![(items, 0)]; // (menu, menu's parent)
while let Some((mut current_menu, parent_index)) = stack.pop() {
while !current_menu.is_empty() {
match current_menu.remove(0) {
MenuItem::Standard(item) => {
let index = list.len();
list.push((item.into(), Vec::new()));
// Add self to parent's submenu
list[parent_index].1.push(index);
}
MenuItem::Separator => {
let item = RawMenuItem {
r#type: ItemType::Separator,
..Default::default()
};
let index = list.len();
list.push((item, Vec::new()));
list[parent_index].1.push(index);
}
MenuItem::Checkmark(item) => {
let index = list.len();
list.push((item.into(), Vec::new()));
list[parent_index].1.push(index);
}
MenuItem::SubMenu(mut item) => {
let submenu = std::mem::replace(&mut item.submenu, Default::default());
let index = list.len();
list.push((item.into(), Vec::with_capacity(submenu.len())));
list[parent_index].1.push(index);
if !submenu.is_empty() {
stack.push((current_menu, parent_index));
stack.push((submenu, index));
break;
}
}
MenuItem::RadioGroup(group) => {
let offset = list.len();
let on_selected = Rc::new(group.select);
for (idx, option) in group.options.into_iter().enumerate() {
let on_selected = on_selected.clone();
let item = RawMenuItem {
r#type: ItemType::Standard,
label: option.label,
enabled: option.enabled,
visible: option.visible,
icon_name: option.icon_name,
icon_data: option.icon_data,
shortcut: option.shortcut,
toggle_type: ToggleType::Radio,
toggle_state: if idx == group.selected {
ToggleState::On
} else {
ToggleState::Off
},
disposition: option.disposition,
on_clicked: Rc::new(move |this, id| {
(on_selected)(this, id - offset);
}),
..Default::default()
};
let index = list.len();
list.push((item, Vec::new()));
list[parent_index].1.push(index);
}
}
}
}
}
list
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_menu_flatten() {
let x: Vec<MenuItem<()>> = vec![
SubMenu {
label: "a".into(),
submenu: vec![
SubMenu {
label: "a1".into(),
submenu: vec![StandardItem {
label: "a1.1".into(),
..Default::default()
}
.into()],
..Default::default()
}
.into(),
StandardItem {
label: "a2".into(),
..Default::default()
}
.into(),
],
..Default::default()
}
.into(),
StandardItem {
label: "b".into(),
..Default::default()
}
.into(),
SubMenu {
label: "c".into(),
submenu: vec![
StandardItem {
label: "c1".into(),
..Default::default()
}
.into(),
SubMenu {
label: "c2".into(),
submenu: vec![StandardItem {
label: "c2.1".into(),
..Default::default()
}
.into()],
..Default::default()
}
.into(),
],
..Default::default()
}
.into(),
];
let r = menu_flatten(x);
let expect: Vec<(RawMenuItem<()>, Vec<usize>)> = vec![
(
RawMenuItem {
label: "".into(),
..Default::default()
},
vec![1, 5, 6],
),
(
RawMenuItem {
label: "a".into(),
..Default::default()
},
vec![2, 4],
),
(
RawMenuItem {
label: "a1".into(),
..Default::default()
},
vec![3],
),
(
RawMenuItem {
label: "a1.1".into(),
..Default::default()
},
vec![],
),
(
RawMenuItem {
label: "a2".into(),
..Default::default()
},
vec![],
),
(
RawMenuItem {
label: "b".into(),
..Default::default()
},
vec![],
),
(
RawMenuItem {
label: "c".into(),
..Default::default()
},
vec![7, 8],
),
(
RawMenuItem {
label: "c1".into(),
..Default::default()
},
vec![],
),
(
RawMenuItem {
label: "c2".into(),
..Default::default()
},
vec![9],
),
(
RawMenuItem {
label: "c2.1".into(),
..Default::default()
},
vec![],
),
];
assert_eq!(r.len(), 10);
assert_eq!(r[0].1, expect[0].1);
assert_eq!(r[1].1, expect[1].1);
assert_eq!(r[2].1, expect[2].1);
assert_eq!(r[3].1, expect[3].1);
assert_eq!(r[4].1, expect[4].1);
assert_eq!(r[5].1, expect[5].1);
assert_eq!(r[6].1, expect[6].1);
assert_eq!(r[7].1, expect[7].1);
assert_eq!(r[8].1, expect[8].1);
assert_eq!(r[9].1, expect[9].1);
assert_eq!(r[0].0.label, expect[0].0.label);
assert_eq!(r[1].0.label, expect[1].0.label);
assert_eq!(r[2].0.label, expect[2].0.label);
assert_eq!(r[3].0.label, expect[3].0.label);
assert_eq!(r[4].0.label, expect[4].0.label);
assert_eq!(r[5].0.label, expect[5].0.label);
assert_eq!(r[6].0.label, expect[6].0.label);
assert_eq!(r[7].0.label, expect[7].0.label);
assert_eq!(r[8].0.label, expect[8].0.label);
assert_eq!(r[9].0.label, expect[9].0.label);
}
}