1use std::fmt;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6
7use tauri::menu::{Menu, MenuItem};
8use tauri::tray::TrayIconBuilder;
9use tauri::{Manager, PhysicalPosition, PhysicalSize, WebviewWindow};
10
11pub const MAIN_WINDOW_LABEL: &str = "main";
13pub const POPOUT_WINDOW_PREFIX: &str = "popout-";
15
16pub fn popout_widget_id(label: &str) -> Option<&str> {
18 label
19 .strip_prefix(POPOUT_WINDOW_PREFIX)
20 .filter(|id| crate::widgets::validate_widget_id(id).is_ok())
21}
22
23pub fn is_app_window(label: &str) -> bool {
25 label == MAIN_WINDOW_LABEL || popout_widget_id(label).is_some()
26}
27
28pub const TRAY_ID: &str = "toolblox-tray";
30const TRAY_OPEN_ID: &str = "toolblox-open";
32const TRAY_QUIT_ID: &str = "toolblox-quit";
34
35#[derive(Default)]
37pub struct LifecycleState {
38 quit_requested: AtomicBool,
40 pending_activation: AtomicBool,
42 pub mini_restore: Mutex<Option<(PhysicalPosition<i32>, PhysicalSize<u32>)>>,
44}
45
46impl LifecycleState {
47 pub fn mark_quit_requested(&self) {
49 self.quit_requested.store(true, Ordering::SeqCst);
50 }
51
52 pub fn quit_requested(&self) -> bool {
54 self.quit_requested.load(Ordering::SeqCst)
55 }
56
57 pub fn take_pending_activation(&self) -> bool {
59 self.pending_activation.swap(false, Ordering::SeqCst)
60 }
61}
62
63#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub enum CloseDecision {
66 HideToTray,
68 Exit,
70}
71
72pub fn decide_close(
75 run_in_background: bool,
76 tray_ready: bool,
77 quit_requested: bool,
78) -> CloseDecision {
79 if run_in_background && tray_ready && !quit_requested {
80 CloseDecision::HideToTray
81 } else {
82 CloseDecision::Exit
83 }
84}
85
86pub fn handle_close_request(
89 window: &WebviewWindow,
90 api: &tauri::CloseRequestApi,
91 state: &LifecycleState,
92 run_in_background: bool,
93) -> Result<CloseDecision, LifecycleError> {
94 let tray_ready = window.app_handle().tray_by_id(TRAY_ID).is_some();
95 let decision = decide_close(run_in_background, tray_ready, state.quit_requested());
96 if decision == CloseDecision::Exit {
97 return Ok(decision);
98 }
99
100 api.prevent_close();
101 if window.set_skip_taskbar(true).is_err() || window.hide().is_err() {
102 let _ = window.set_skip_taskbar(false);
103 let _ = window.show();
104 return Err(LifecycleError::Hide);
105 }
106 Ok(decision)
107}
108
109pub fn restore_main_window(app: &tauri::AppHandle) -> Result<(), LifecycleError> {
111 let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) else {
112 return Err(LifecycleError::MissingMainWindow);
113 };
114 window
115 .set_skip_taskbar(false)
116 .map_err(|_| LifecycleError::Restore)?;
117 window.unminimize().map_err(|_| LifecycleError::Restore)?;
118 window.show().map_err(|_| LifecycleError::Restore)?;
119 window.set_focus().map_err(|_| LifecycleError::Restore)?;
120 Ok(())
121}
122
123pub fn activate_or_defer(app: &tauri::AppHandle, state: &LifecycleState) {
125 if restore_main_window(app).is_err() {
126 state.pending_activation.store(true, Ordering::SeqCst);
127 }
128}
129
130pub fn apply_pending_activation(
132 app: &tauri::AppHandle,
133 state: &LifecycleState,
134) -> Result<(), LifecycleError> {
135 if state.take_pending_activation() {
136 restore_main_window(app)?;
137 }
138 Ok(())
139}
140
141pub fn install_tray(
143 app: &tauri::AppHandle,
144 state: Arc<LifecycleState>,
145 before_quit: Arc<dyn Fn() + Send + Sync>,
146) -> Result<(), LifecycleError> {
147 if app.tray_by_id(TRAY_ID).is_some() {
148 return Ok(());
149 }
150
151 let open = MenuItem::with_id(app, TRAY_OPEN_ID, "Open Toolblox", true, None::<&str>)
152 .map_err(|_| LifecycleError::Tray)?;
153 let quit = MenuItem::with_id(app, TRAY_QUIT_ID, "Quit", true, None::<&str>)
154 .map_err(|_| LifecycleError::Tray)?;
155 let menu = Menu::with_items(app, &[&open, &quit]).map_err(|_| LifecycleError::Tray)?;
156
157 let quit_state = state.clone();
158 let mut builder = TrayIconBuilder::with_id(TRAY_ID)
159 .tooltip("Toolblox")
160 .menu(&menu)
161 .show_menu_on_left_click(false)
162 .on_menu_event(move |app, event| match event.id.as_ref() {
163 TRAY_OPEN_ID => {
164 activate_or_defer(app, &quit_state);
165 }
166 TRAY_QUIT_ID => {
167 quit_state.mark_quit_requested();
168 before_quit();
169 app.exit(0);
170 }
171 _ => {}
172 });
173 #[cfg(target_os = "macos")]
174 {
175 builder = builder
176 .icon(tauri::include_image!("icons/tray-template.png"))
177 .icon_as_template(true);
178 }
179 #[cfg(not(target_os = "macos"))]
180 if let Some(icon) = app.default_window_icon() {
181 builder = builder.icon(icon.clone());
182 }
183 builder.build(app).map_err(|_| LifecycleError::Tray)?;
184 Ok(())
185}
186
187#[cfg(test)]
189pub trait AutostartBackend {
190 fn is_enabled(&self) -> Result<bool, String>;
191 fn enable(&self) -> Result<(), String>;
192 fn disable(&self) -> Result<(), String>;
193}
194
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
197#[cfg(test)]
198pub enum AutostartChange {
199 None,
200 Enabled,
201 Disabled,
202}
203
204#[cfg(test)]
206pub fn reconcile_autostart(
207 desired: bool,
208 backend: &impl AutostartBackend,
209) -> Result<AutostartChange, LifecycleError> {
210 let current = backend
211 .is_enabled()
212 .map_err(|_| LifecycleError::Autostart)?;
213 match (current, desired) {
214 (false, true) => {
215 backend.enable().map_err(|_| LifecycleError::Autostart)?;
216 Ok(AutostartChange::Enabled)
217 }
218 (true, false) => {
219 backend.disable().map_err(|_| LifecycleError::Autostart)?;
220 Ok(AutostartChange::Disabled)
221 }
222 _ => Ok(AutostartChange::None),
223 }
224}
225
226#[derive(Clone, Copy, Debug, Eq, PartialEq)]
228pub enum LifecycleError {
229 Tray,
230 Hide,
231 Restore,
232 MissingMainWindow,
233 #[cfg(test)]
234 Autostart,
235}
236
237impl fmt::Display for LifecycleError {
238 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
239 formatter.write_str(match self {
240 Self::Tray => "The tray icon couldn't open. Would turning off background mode help?",
241 Self::Hide => "Toolblox couldn't hide its window. Would closing it again help?",
242 Self::Restore => "Toolblox couldn't restore its window. Would reopening it help?",
243 Self::MissingMainWindow => {
244 "The Toolblox window isn't ready yet. Would waiting for startup help?"
245 }
246 #[cfg(test)]
247 Self::Autostart => {
248 "The startup setting couldn't be changed. Does the operating system allow startup apps?"
249 }
250 })
251 }
252}
253
254impl std::error::Error for LifecycleError {}
255
256#[cfg(test)]
257mod tests {
258 use std::cell::Cell;
259
260 use super::*;
261
262 #[test]
263 fn window_hides_only_when_a_tray_recovery_path_exists() {
264 assert_eq!(decide_close(true, true, false), CloseDecision::HideToTray);
265 assert_eq!(decide_close(true, false, false), CloseDecision::Exit);
266 assert_eq!(decide_close(false, true, false), CloseDecision::Exit);
267 assert_eq!(decide_close(true, true, true), CloseDecision::Exit);
268 }
269
270 struct FakeAutostart {
271 enabled: Cell<bool>,
272 }
273
274 impl AutostartBackend for FakeAutostart {
275 fn is_enabled(&self) -> Result<bool, String> {
276 Ok(self.enabled.get())
277 }
278
279 fn enable(&self) -> Result<(), String> {
280 self.enabled.set(true);
281 Ok(())
282 }
283
284 fn disable(&self) -> Result<(), String> {
285 self.enabled.set(false);
286 Ok(())
287 }
288 }
289
290 #[test]
291 fn autostart_changes_only_when_needed() {
292 let backend = FakeAutostart {
293 enabled: Cell::new(false),
294 };
295 assert_eq!(
296 reconcile_autostart(true, &backend).unwrap(),
297 AutostartChange::Enabled
298 );
299 assert_eq!(
300 reconcile_autostart(true, &backend).unwrap(),
301 AutostartChange::None
302 );
303 assert_eq!(
304 reconcile_autostart(false, &backend).unwrap(),
305 AutostartChange::Disabled
306 );
307 }
308
309 #[test]
310 fn deferred_activation_is_consumed_once() {
311 let state = LifecycleState::default();
312 state.pending_activation.store(true, Ordering::SeqCst);
313 assert!(state.take_pending_activation());
314 assert!(!state.take_pending_activation());
315 }
316
317 #[test]
318 fn only_main_and_popout_windows_show_the_app() {
319 assert!(is_app_window("main"));
320 assert!(is_app_window("popout-autoclicker"));
321 assert_eq!(popout_widget_id("popout-autoclicker"), Some("autoclicker"));
322 assert!(!is_app_window("popout-"));
323 assert!(!is_app_window("popout-Bad-Id"));
324 assert!(!is_app_window("roblox-login"));
325 }
326}