Skip to content

Commit 441f964

Browse files
authored
feat(core/tauri): add try_get_item for SystemTray and WindowMenu, closes #5491 (#6408)
* feat: try_get_item() for window menu Add a method in the MenuHandle struct, that will return an Optional MenuItemHandle feat: try_get_item() for systemtray Add a method in the SystemTrayHandle struct, that will return an Optional SystemTrayMenuItemHandle docs: features documented in ./changes/minor.md fix: suggested changes fix CI * Update .changes/tray_get_item.md ---------
1 parent 2c1fd57 commit 441f964

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

.changes/tray_get_item.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'tauri': minor
3+
---
4+
5+
Add `MenuHandle::try_get_item` and `SystemTrayHandle::try_get_item` which returns a `Option` instead of panicking.

core/tauri/src/app/tray.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,19 @@ impl<R: Runtime> SystemTrayHandle<R> {
610610
panic!("item id not found")
611611
}
612612

613+
/// Attempts to get a handle to the menu item that has the specified `id`, return an error if `id` is not found.
614+
pub fn try_get_item(&self, id: MenuIdRef<'_>) -> Option<SystemTrayMenuItemHandle<R>> {
615+
self
616+
.ids
617+
.lock()
618+
.unwrap()
619+
.iter()
620+
.find(|i| i.1 == id)
621+
.map(|i| SystemTrayMenuItemHandle {
622+
id: *i.0,
623+
tray_handler: self.inner.clone(),
624+
})
625+
}
613626
/// Updates the tray icon.
614627
pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
615628
self.inner.set_icon(icon.try_into()?).map_err(Into::into)

core/tauri/src/window/menu.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,20 @@ impl<R: Runtime> MenuHandle<R> {
8080
panic!("item id not found")
8181
}
8282

83+
/// Attempts to get a handle to the menu item that has the specified `id`, return an error if `id` is not found.
84+
pub fn try_get_item(&self, id: MenuIdRef<'_>) -> Option<MenuItemHandle<R>> {
85+
self
86+
.ids
87+
.lock()
88+
.unwrap()
89+
.iter()
90+
.find(|i| i.1 == id)
91+
.map(|i| MenuItemHandle {
92+
id: *i.0,
93+
dispatcher: self.dispatcher.clone(),
94+
})
95+
}
96+
8397
/// Shows the menu.
8498
pub fn show(&self) -> crate::Result<()> {
8599
self.dispatcher.show_menu().map_err(Into::into)

0 commit comments

Comments
 (0)