1#[cfg(feature = "serde")]
7use std::fs::{self, File};
8#[cfg(feature = "serde")]
9use std::io::Write;
10#[cfg(feature = "serde")]
11use std::path::{Path, PathBuf};
12
13use crate::displays::DisplayInfo;
14#[cfg(feature = "serde")]
15use crate::error::{GuiError, GuiResult};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum WindowShowState {
21 #[default]
23 Normal,
24 Maximized,
26 Minimized,
28 Fullscreen,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35pub struct RectGeometry {
36 pub x: i32,
38 pub y: i32,
40 pub width: u32,
42 pub height: u32,
44}
45
46impl RectGeometry {
47 pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
49 Self {
50 x,
51 y,
52 width,
53 height,
54 }
55 }
56
57 pub const MIN_WIDTH: u32 = 200;
59 pub const MIN_HEIGHT: u32 = 150;
61
62 pub fn ensure_minimum_size(&self) -> Self {
64 Self {
65 x: self.x,
66 y: self.y,
67 width: self.width.max(Self::MIN_WIDTH),
68 height: self.height.max(Self::MIN_HEIGHT),
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
76pub struct WindowGeometry {
77 pub show_state: WindowShowState,
79 pub floating_bounds: RectGeometry,
81 pub display_id: Option<u32>,
83 pub schema_version: u32,
85}
86
87impl Default for WindowGeometry {
88 fn default() -> Self {
89 Self {
90 show_state: WindowShowState::Normal,
91 floating_bounds: RectGeometry::new(100, 100, 800, 600),
92 display_id: None,
93 schema_version: 1,
94 }
95 }
96}
97
98impl WindowGeometry {
99 pub fn new_floating(x: i32, y: i32, width: u32, height: u32) -> Self {
101 Self {
102 show_state: WindowShowState::Normal,
103 floating_bounds: RectGeometry::new(x, y, width, height).ensure_minimum_size(),
104 display_id: None,
105 schema_version: 1,
106 }
107 }
108
109 pub fn new_maximized(
111 floating_x: i32,
112 floating_y: i32,
113 floating_width: u32,
114 floating_height: u32,
115 ) -> Self {
116 Self {
117 show_state: WindowShowState::Maximized,
118 floating_bounds: RectGeometry::new(
119 floating_x,
120 floating_y,
121 floating_width,
122 floating_height,
123 )
124 .ensure_minimum_size(),
125 display_id: None,
126 schema_version: 1,
127 }
128 }
129}
130
131pub fn clamp_to_displays(
143 requested: &RectGeometry,
144 displays: &[DisplayInfo],
145 titlebar_height: u32,
146) -> RectGeometry {
147 let safe_req = requested.ensure_minimum_size();
148
149 if displays.is_empty() {
150 return safe_req;
151 }
152
153 let primary = displays.iter().find(|d| d.primary).unwrap_or(&displays[0]);
154 let titlebar_h = titlebar_height.max(24) as i32;
155 let required_visible_px = (safe_req.width / 2).clamp(1, 100);
158
159 let mut best_overlap_display: Option<&DisplayInfo> = None;
161 let mut max_titlebar_visible_px = 0;
162
163 for display in displays {
164 let wa = &display.work_area;
165 let wa_right = wa.x + wa.width;
166 let wa_bottom = wa.y + wa.height;
167
168 let tb_left = safe_req.x;
170 let tb_right = safe_req.x + safe_req.width as i32;
171 let tb_top = safe_req.y;
172 let tb_bottom = safe_req.y + titlebar_h;
173
174 let inter_left = tb_left.max(wa.x);
176 let inter_right = tb_right.min(wa_right);
177 let inter_top = tb_top.max(wa.y);
178 let inter_bottom = tb_bottom.min(wa_bottom);
179
180 if inter_right > inter_left && inter_bottom > inter_top {
181 let visible_w = (inter_right - inter_left) as u32;
182 if visible_w > max_titlebar_visible_px {
183 max_titlebar_visible_px = visible_w;
184 best_overlap_display = Some(display);
185 }
186 }
187 }
188
189 if let Some(display) =
192 best_overlap_display.filter(|_| max_titlebar_visible_px >= required_visible_px)
193 {
194 let wa = &display.work_area;
195 let clamped_x = safe_req.x;
196 let mut clamped_y = safe_req.y;
197
198 if clamped_y < wa.y {
200 clamped_y = wa.y;
201 }
202
203 let max_y = (wa.y + wa.height - titlebar_h).max(wa.y);
206 if clamped_y > max_y {
207 clamped_y = max_y;
208 }
209
210 let clamped_w = safe_req.width.min(wa.width.max(0) as u32);
212 let clamped_h = safe_req.height.min(wa.height.max(0) as u32);
213
214 RectGeometry::new(clamped_x, clamped_y, clamped_w, clamped_h)
215 } else {
216 let p_wa = &primary.work_area;
218 let clamped_w = safe_req.width.min(p_wa.width.max(0) as u32);
219 let clamped_h = safe_req.height.min(p_wa.height.max(0) as u32);
220
221 let center_x = p_wa.x + ((p_wa.width.saturating_sub(clamped_w as i32)) / 2);
222 let center_y = p_wa.y + ((p_wa.height.saturating_sub(clamped_h as i32)) / 2);
223
224 RectGeometry::new(center_x, center_y, clamped_w, clamped_h)
225 }
226}
227
228#[cfg(feature = "serde")]
232pub fn get_window_state_path(app_data_root: &Path, app_name: &str, window_name: &str) -> PathBuf {
233 app_data_root
234 .join(app_name)
235 .join(format!("{}_window_state.json", window_name))
236}
237
238#[cfg(feature = "serde")]
242pub fn save_window_geometry_to_path(
243 target_path: &Path,
244 geometry: &WindowGeometry,
245) -> GuiResult<()> {
246 if let Some(parent) = target_path.parent() {
247 fs::create_dir_all(parent)
248 .map_err(|e| GuiError::Backend(format!("Failed to create state dir: {e}")))?;
249 }
250
251 let temp_path = target_path.with_extension(format!("tmp.{}", std::process::id()));
252
253 let json_data = serde_json::to_string_pretty(geometry)
254 .map_err(|e| GuiError::Backend(format!("Failed to serialize window geometry: {e}")))?;
255
256 {
257 let mut file = File::create(&temp_path)
258 .map_err(|e| GuiError::Backend(format!("Failed to create temp state file: {e}")))?;
259 file.write_all(json_data.as_bytes())
260 .map_err(|e| GuiError::Backend(format!("Failed to write temp state file: {e}")))?;
261 file.sync_all()
262 .map_err(|e| GuiError::Backend(format!("Failed to sync temp state file: {e}")))?;
263 }
264
265 fs::rename(&temp_path, target_path)
266 .map_err(|e| GuiError::Backend(format!("Failed to atomically replace state file: {e}")))?;
267
268 Ok(())
269}
270
271#[cfg(feature = "serde")]
276pub fn load_window_geometry_from_path(
277 target_path: &Path,
278 displays: &[DisplayInfo],
279) -> WindowGeometry {
280 if !target_path.exists() {
281 return WindowGeometry::default();
282 }
283
284 let content = match fs::read_to_string(target_path) {
285 Ok(c) => c,
286 Err(_) => return WindowGeometry::default(),
287 };
288
289 let parsed: WindowGeometry = match serde_json::from_str(&content) {
290 Ok(g) => g,
291 Err(_) => return WindowGeometry::default(),
292 };
293 if parsed.schema_version != 1 {
294 return WindowGeometry::default();
295 }
296
297 let clamped_bounds = clamp_to_displays(&parsed.floating_bounds, displays, 32);
298
299 WindowGeometry {
300 show_state: parsed.show_state,
301 floating_bounds: clamped_bounds,
302 display_id: parsed.display_id,
303 schema_version: 1,
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use crate::displays::DisplayRect;
311
312 fn sample_displays() -> Vec<DisplayInfo> {
313 vec![
314 DisplayInfo {
315 id: 1,
316 name: "Primary Display".to_string(),
317 bounds: DisplayRect {
318 x: 0,
319 y: 0,
320 width: 1920,
321 height: 1080,
322 },
323 work_area: DisplayRect {
324 x: 0,
325 y: 40,
326 width: 1920,
327 height: 1040,
328 },
329 scale_factor: 1.0,
330 primary: true,
331 },
332 DisplayInfo {
333 id: 2,
334 name: "Secondary Display".to_string(),
335 bounds: DisplayRect {
336 x: 1920,
337 y: 0,
338 width: 1920,
339 height: 1080,
340 },
341 work_area: DisplayRect {
342 x: 1920,
343 y: 0,
344 width: 1920,
345 height: 1080,
346 },
347 scale_factor: 1.0,
348 primary: false,
349 },
350 ]
351 }
352
353 #[test]
354 fn default_geometry_invariants() {
355 let geom = WindowGeometry::default();
356 assert_eq!(geom.show_state, WindowShowState::Normal);
357 assert_eq!(geom.floating_bounds.width, 800);
358 assert_eq!(geom.floating_bounds.height, 600);
359 assert_eq!(geom.schema_version, 1);
360 }
361
362 #[test]
363 #[cfg(feature = "serde")]
364 fn serialization_round_trip() {
365 let geom = WindowGeometry::new_maximized(120, 150, 1024, 768);
366 let serialized = serde_json::to_string(&geom).expect("serialize");
367 let deserialized: WindowGeometry = serde_json::from_str(&serialized).expect("deserialize");
368 assert_eq!(geom, deserialized);
369 }
370
371 #[test]
372 fn clamp_within_primary_work_area() {
373 let displays = sample_displays();
374 let req = RectGeometry::new(100, 20, 800, 600); let clamped = clamp_to_displays(&req, &displays, 30);
376 assert_eq!(clamped.y, 40); assert_eq!(clamped.x, 100);
378 assert_eq!(clamped.width, 800);
379 assert_eq!(clamped.height, 600);
380 }
381
382 #[test]
383 fn clamp_secondary_display_when_connected() {
384 let displays = sample_displays();
385 let req = RectGeometry::new(2000, 100, 800, 600);
386 let clamped = clamp_to_displays(&req, &displays, 30);
387 assert_eq!(clamped.x, 2000);
388 assert_eq!(clamped.y, 100);
389 }
390
391 #[test]
392 fn clamp_keeps_a_position_only_when_enough_titlebar_is_grabbable() {
393 let displays = vec![sample_displays()[0].clone()];
396 let req = RectGeometry::new(1919, 100, 800, 600);
399 let clamped = clamp_to_displays(&req, &displays, 30);
400 assert_ne!(clamped.x, 1919, "a sliver must not count as visible");
401 assert!(clamped.x >= 0 && clamped.x < 1920);
402 assert!(clamped.y >= 40);
403
404 let req = RectGeometry::new(1800, 100, 800, 600);
406 let clamped = clamp_to_displays(&req, &displays, 30);
407 assert_eq!(clamped.x, 1800);
408 }
409
410 #[test]
411 fn clamp_off_screen_disconnected_monitor_recovers_to_primary() {
412 let displays = vec![sample_displays()[0].clone()]; let req = RectGeometry::new(2500, 200, 800, 600); let clamped = clamp_to_displays(&req, &displays, 30);
415 assert!(clamped.x >= 0 && clamped.x < 1920);
417 assert!(clamped.y >= 40 && clamped.y < 1080);
418 assert_eq!(clamped.width, 800);
419 assert_eq!(clamped.height, 600);
420 }
421
422 #[test]
423 fn ensure_minimum_size_clamps_small_values() {
424 let req = RectGeometry::new(50, 50, 50, 20);
425 let safe = req.ensure_minimum_size();
426 assert_eq!(safe.width, RectGeometry::MIN_WIDTH);
427 assert_eq!(safe.height, RectGeometry::MIN_HEIGHT);
428 }
429
430 #[test]
431 #[cfg(feature = "serde")]
432 fn atomic_save_and_load_round_trip() {
433 let temp_dir =
434 std::env::temp_dir().join(format!("native_gui_test_geom_{}", std::process::id()));
435 let state_path = temp_dir.join("test_window_state.json");
436 let displays = sample_displays();
437
438 let original = WindowGeometry::new_floating(150, 180, 900, 650);
439 save_window_geometry_to_path(&state_path, &original).expect("save should succeed");
440
441 let loaded = load_window_geometry_from_path(&state_path, &displays);
442 assert_eq!(loaded.show_state, original.show_state);
443 assert_eq!(loaded.floating_bounds, original.floating_bounds);
444
445 fs::write(&state_path, "invalid json content").expect("write corrupt");
447 let fallback = load_window_geometry_from_path(&state_path, &displays);
448 assert_eq!(fallback, WindowGeometry::default());
449
450 let _ = fs::remove_dir_all(&temp_dir);
451 }
452}