-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmain.rs
227 lines (206 loc) · 7.7 KB
/
main.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
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use chrono::Duration;
use serde::Serialize;
use tauri::Manager;
use tauri::{CustomMenuItem, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem};
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
#[allow(clippy::needless_pass_by_value)]
#[tauri::command]
fn greet(
_window: tauri::Window,
app_handle: tauri::AppHandle,
name: &str,
password: &str,
email: &str,
) -> String {
let item_handle = app_handle.tray_handle().get_item("user");
item_handle.set_title(format!("User: {}", name)).unwrap();
format!("hello {}, {}, password: {}", name, email, password)
}
#[allow(clippy::needless_pass_by_value)]
#[tauri::command]
fn set_menu_item(app_handle: tauri::AppHandle, title: &str) {
let item_handle = app_handle.tray_handle().get_item("dynamic-item");
item_handle.set_title(title).unwrap();
}
// there's no way to grab the current menu, and add to it, creating
// an evergrowing menu. so, we rebuild the initial menu and add an item.
// this means we'll only add one item, but to add an arbitrary number,
// make this command accept an array of items.
// also, you probably would want to inject the new items in a specific place,
// so you'd have to split the initial menu to [start] [your content] [end],
// where 'end' contains things like "show" and "quit".
#[allow(clippy::needless_pass_by_value)]
#[tauri::command]
fn add_menu_item(app_handle: tauri::AppHandle, id: &str, title: &str) {
let mut menu = build_menu();
let item = CustomMenuItem::new(id.to_string(), title);
menu = menu.add_item(item);
app_handle.tray_handle().set_menu(menu).unwrap();
}
#[allow(clippy::needless_pass_by_value)]
#[tauri::command]
fn set_icon(app_handle: tauri::AppHandle, name: &str) {
match name {
"notification" => app_handle
.tray_handle()
.set_icon(tauri::Icon::Raw(
include_bytes!("../icons/32x32-notification.png").to_vec(),
))
.unwrap(),
_ => app_handle
.tray_handle()
.set_icon(tauri::Icon::Raw(
include_bytes!("../icons/32x32.png").to_vec(),
))
.unwrap(),
};
}
#[tauri::command]
fn interval_action(msg: &str) -> String {
let out = format!("interval_action: {}", chrono::Local::now().to_rfc3339());
println!("js -> rs {} - {}", out, msg);
out
}
#[derive(Serialize)]
struct Content {
body: String,
}
#[tauri::command]
async fn api_request(msg: &str) -> Result<Vec<Content>, String> {
println!("js -> rs api_request - {}", msg);
let res = reqwest::get("https://example.com")
.await
.map_err(|e| e.to_string())?;
let out = res.text().await.map_err(|e| e.to_string())?;
Ok(vec![Content { body: out }])
}
#[allow(dead_code)]
#[tauri::command]
fn init_process(window: tauri::Window) {
std::thread::spawn(move || loop {
window
.emit(
"beep",
format!("beep: {}", chrono::Local::now().to_rfc3339()),
)
.unwrap();
thread::sleep(Duration::seconds(5).to_std().unwrap());
});
}
fn build_menu() -> SystemTrayMenu {
let menuitem_quit = CustomMenuItem::new("quit".to_string(), "Quit");
let menuitem_show = CustomMenuItem::new("show".to_string(), "Show");
SystemTrayMenu::new()
.add_item(menuitem_show)
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("user".to_string(), "User"))
.add_item(CustomMenuItem::new("rs-count".to_string(), "RS count"))
.add_item(CustomMenuItem::new("dynamic-item".to_string(), "Change me"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(menuitem_quit)
}
fn main() {
#[allow(clippy::mutex_integer)]
let count = Arc::new(Mutex::new(0));
let tray_menu = build_menu();
tauri::Builder::default()
.system_tray(SystemTray::new().with_menu(tray_menu))
.on_system_tray_event(move |app, event| match event {
SystemTrayEvent::LeftClick {
position: _,
size: _,
..
} => {
// this demos how to mutate and set some local state that is
// bound to `main`, with mutex and arc.
println!("system tray received a left click");
let item_handle = app.tray_handle().get_item("rs-count");
let mut c = count.lock().unwrap();
*c += 1;
item_handle.set_title(format!("RS count: {}", c)).unwrap();
}
SystemTrayEvent::RightClick {
position: _,
size: _,
..
} => {
println!("system tray received a right click");
}
SystemTrayEvent::DoubleClick {
position: _,
size: _,
..
} => {
println!("system tray received a double click");
}
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"quit" => {
std::process::exit(0);
}
"show" => {
let w = app.get_window("main").unwrap();
w.show().unwrap();
// because the window shows in a specific workspace and the user
// can hide it and move to another, it will next show in the original
// workspace it was opened in.
// this is important for the window to always show in whatever workspace
// the user moved to and is active in.
w.set_focus().unwrap();
}
_ => {}
},
_ => {}
})
.on_window_event(|event| match event.event() {
tauri::WindowEvent::CloseRequested { api, .. } => {
// don't kill the app when the user clicks close. this is important
event.window().hide().unwrap();
api.prevent_close();
}
tauri::WindowEvent::Focused(false) => {
// hide the window automaticall when the user
// clicks out. this is for a matter of taste.
event.window().hide().unwrap();
}
_ => {}
})
.setup(|app| {
// don't show on the taskbar/springboard
// this is purely a personal taste thing
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let window = app.get_window("main").unwrap();
// this is a workaround for the window to always show in current workspace.
// see https://github.com/tauri-apps/tauri/issues/2801
window.set_always_on_top(true).unwrap();
// watch out! forever loop, every 5s emit an event
// to the JS side, which has to subscribe on the event ID.
std::thread::spawn(move || loop {
window
.emit(
"rs_js_emit",
format!("beep: {}", chrono::Local::now().to_rfc3339()),
)
.unwrap();
println!("rs -> js emit");
thread::sleep(Duration::seconds(5).to_std().unwrap());
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
greet,
set_menu_item,
add_menu_item,
interval_action,
api_request,
set_icon
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}