2
2
// SPDX-License-Identifier: Apache-2.0
3
3
// SPDX-License-Identifier: MIT
4
4
5
- use std:: path:: PathBuf ;
5
+ use std:: { collections :: HashMap , path:: PathBuf , sync :: Mutex } ;
6
6
7
7
use serde:: Deserialize ;
8
8
@@ -14,11 +14,15 @@ use crate::{
14
14
plugin:: { Builder , TauriPlugin } ,
15
15
resources:: ResourceId ,
16
16
tray:: TrayIconBuilder ,
17
- AppHandle , Manager , Runtime , Webview ,
17
+ AppHandle , Manager , Runtime , State , Webview ,
18
18
} ;
19
19
20
20
use super :: { TrayIcon , TrayIconEvent } ;
21
21
22
+ pub ( crate ) struct TrayIcons {
23
+ pub ( crate ) icons : Mutex < HashMap < String , ResourceId > > ,
24
+ }
25
+
22
26
#[ derive( Deserialize ) ]
23
27
#[ serde( rename_all = "camelCase" ) ]
24
28
struct TrayIconOptions {
@@ -36,6 +40,7 @@ struct TrayIconOptions {
36
40
#[ command( root = "crate" ) ]
37
41
fn new < R : Runtime > (
38
42
webview : Webview < R > ,
43
+ icons : State < ' _ , TrayIcons > ,
39
44
options : TrayIconOptions ,
40
45
handler : Channel < TrayIconEvent > ,
41
46
) -> crate :: Result < ( ResourceId , String ) > {
@@ -91,20 +96,35 @@ fn new<R: Runtime>(
91
96
let id = tray. id ( ) . as_ref ( ) . to_string ( ) ;
92
97
let rid = resources_table. add ( tray) ;
93
98
99
+ icons. icons . lock ( ) . unwrap ( ) . insert ( id. clone ( ) , rid) ;
100
+
94
101
Ok ( ( rid, id) )
95
102
}
96
103
97
104
#[ command( root = "crate" ) ]
98
105
fn get_by_id < R : Runtime > (
99
106
app : AppHandle < R > ,
100
107
webview : Webview < R > ,
108
+ icons : State < ' _ , TrayIcons > ,
101
109
id : & str ,
102
110
) -> crate :: Result < Option < ResourceId > > {
111
+ // if the icon was created by this plugin, return the resource id
112
+ // this lets a getById call match the rid of a TrayIcon.new call
113
+ // which allows it to close a previously created icon
114
+ if let Some ( rid) = icons. icons . lock ( ) . unwrap ( ) . get ( id) {
115
+ return Ok ( Some ( * rid) ) ;
116
+ }
117
+
103
118
let tray = app. tray_by_id ( id) ;
104
119
let maybe_rid = tray. map ( |tray| {
105
120
let mut resources_table = webview. resources_table ( ) ;
106
121
resources_table. add ( tray)
107
122
} ) ;
123
+
124
+ if let Some ( rid) = maybe_rid {
125
+ icons. icons . lock ( ) . unwrap ( ) . insert ( id. to_string ( ) , rid) ;
126
+ }
127
+
108
128
Ok ( maybe_rid)
109
129
}
110
130
@@ -226,6 +246,12 @@ fn set_show_menu_on_left_click<R: Runtime>(
226
246
227
247
pub ( crate ) fn init < R : Runtime > ( ) -> TauriPlugin < R > {
228
248
Builder :: new ( "tray" )
249
+ . setup ( |app, _api| {
250
+ app. manage ( TrayIcons {
251
+ icons : Default :: default ( ) ,
252
+ } ) ;
253
+ Ok ( ( ) )
254
+ } )
229
255
. invoke_handler ( crate :: generate_handler![
230
256
#![ plugin( tray) ]
231
257
new,
0 commit comments