native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Window state and geometry persistence.
//!
//! Provides data structures and multi-monitor clamping algorithms for persisting
//! and restoring window positions, sizes, and maximized states across application sessions.

#[cfg(feature = "serde")]
use std::fs::{self, File};
#[cfg(feature = "serde")]
use std::io::Write;
#[cfg(feature = "serde")]
use std::path::{Path, PathBuf};

use crate::displays::DisplayInfo;
#[cfg(feature = "serde")]
use crate::error::{GuiError, GuiResult};

/// Window display state (normal, maximized, minimized, or fullscreen).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WindowShowState {
    /// Normal floating window.
    #[default]
    Normal,
    /// Window is maximized to fill the display work area.
    Maximized,
    /// Window is minimized to the taskbar/dock.
    Minimized,
    /// Window is in borderless fullscreen mode.
    Fullscreen,
}

/// 2D rectangle in logical desktop coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RectGeometry {
    /// Horizontal offset from desktop origin in DIPs.
    pub x: i32,
    /// Vertical offset from desktop origin in DIPs.
    pub y: i32,
    /// Width in DIPs.
    pub width: u32,
    /// Height in DIPs.
    pub height: u32,
}

impl RectGeometry {
    /// Creates a new rectangle.
    pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Minimum width allowed for a window.
    pub const MIN_WIDTH: u32 = 200;
    /// Minimum height allowed for a window.
    pub const MIN_HEIGHT: u32 = 150;

    /// Clamps width and height to safe non-degenerate minimum dimensions.
    pub fn ensure_minimum_size(&self) -> Self {
        Self {
            x: self.x,
            y: self.y,
            width: self.width.max(Self::MIN_WIDTH),
            height: self.height.max(Self::MIN_HEIGHT),
        }
    }
}

/// Persistent window geometry specification.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WindowGeometry {
    /// The window state when closed (e.g. Normal or Maximized).
    pub show_state: WindowShowState,
    /// The floating (restored) bounds, even if currently maximized.
    pub floating_bounds: RectGeometry,
    /// Identifier of the display monitor the window last resided on, if available.
    pub display_id: Option<u32>,
    /// Schema version for format migration.
    pub schema_version: u32,
}

impl Default for WindowGeometry {
    fn default() -> Self {
        Self {
            show_state: WindowShowState::Normal,
            floating_bounds: RectGeometry::new(100, 100, 800, 600),
            display_id: None,
            schema_version: 1,
        }
    }
}

impl WindowGeometry {
    /// Creates a new normal floating window geometry.
    pub fn new_floating(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            show_state: WindowShowState::Normal,
            floating_bounds: RectGeometry::new(x, y, width, height).ensure_minimum_size(),
            display_id: None,
            schema_version: 1,
        }
    }

    /// Creates a geometry for a maximized window, remembering its floating restored bounds.
    pub fn new_maximized(
        floating_x: i32,
        floating_y: i32,
        floating_width: u32,
        floating_height: u32,
    ) -> Self {
        Self {
            show_state: WindowShowState::Maximized,
            floating_bounds: RectGeometry::new(
                floating_x,
                floating_y,
                floating_width,
                floating_height,
            )
            .ensure_minimum_size(),
            display_id: None,
            schema_version: 1,
        }
    }
}

/// Clamps a requested window geometry against connected displays to ensure titlebar accessibility.
///
/// # Invariants
/// 1. A display keeps the requested position only when at least
///    `min(100, width / 2)` pixels of the titlebar are visible inside that
///    display's work area — a sliver of a titlebar is not a grabbable one.
/// 2. If no display can satisfy invariant 1 (for example a disconnected
///    external monitor), the window is centered within the primary display's
///    work area.
/// 3. The titlebar's top edge is clamped to `y >= work_area.y`, ensuring
///    close/minimize controls are clickable.
pub fn clamp_to_displays(
    requested: &RectGeometry,
    displays: &[DisplayInfo],
    titlebar_height: u32,
) -> RectGeometry {
    let safe_req = requested.ensure_minimum_size();

    if displays.is_empty() {
        return safe_req;
    }

    let primary = displays.iter().find(|d| d.primary).unwrap_or(&displays[0]);
    let titlebar_h = titlebar_height.max(24) as i32;
    // A titlebar needs a real grab strip, not a single visible pixel; a very
    // narrow window needs less than the 100 px default.
    let required_visible_px = (safe_req.width / 2).clamp(1, 100);

    // Check intersection with any display work area
    let mut best_overlap_display: Option<&DisplayInfo> = None;
    let mut max_titlebar_visible_px = 0;

    for display in displays {
        let wa = &display.work_area;
        let wa_right = wa.x + wa.width;
        let wa_bottom = wa.y + wa.height;

        // Titlebar bounds
        let tb_left = safe_req.x;
        let tb_right = safe_req.x + safe_req.width as i32;
        let tb_top = safe_req.y;
        let tb_bottom = safe_req.y + titlebar_h;

        // Overlap calculation
        let inter_left = tb_left.max(wa.x);
        let inter_right = tb_right.min(wa_right);
        let inter_top = tb_top.max(wa.y);
        let inter_bottom = tb_bottom.min(wa_bottom);

        if inter_right > inter_left && inter_bottom > inter_top {
            let visible_w = (inter_right - inter_left) as u32;
            if visible_w > max_titlebar_visible_px {
                max_titlebar_visible_px = visible_w;
                best_overlap_display = Some(display);
            }
        }
    }

    // Keep the position only for a display where enough of the titlebar is
    // actually reachable.
    if let Some(display) =
        best_overlap_display.filter(|_| max_titlebar_visible_px >= required_visible_px)
    {
        let wa = &display.work_area;
        let clamped_x = safe_req.x;
        let mut clamped_y = safe_req.y;

        // Ensure titlebar top is not hidden under top panel
        if clamped_y < wa.y {
            clamped_y = wa.y;
        }

        // Ensure titlebar is not pushed below bottom of work area, and never
        // above its top edge (a short work area must not invert the clamp).
        let max_y = (wa.y + wa.height - titlebar_h).max(wa.y);
        if clamped_y > max_y {
            clamped_y = max_y;
        }

        // Ensure window width fits within work area
        let clamped_w = safe_req.width.min(wa.width.max(0) as u32);
        let clamped_h = safe_req.height.min(wa.height.max(0) as u32);

        RectGeometry::new(clamped_x, clamped_y, clamped_w, clamped_h)
    } else {
        // Off-screen: center within primary display work area
        let p_wa = &primary.work_area;
        let clamped_w = safe_req.width.min(p_wa.width.max(0) as u32);
        let clamped_h = safe_req.height.min(p_wa.height.max(0) as u32);

        let center_x = p_wa.x + ((p_wa.width.saturating_sub(clamped_w as i32)) / 2);
        let center_y = p_wa.y + ((p_wa.height.saturating_sub(clamped_h as i32)) / 2);

        RectGeometry::new(center_x, center_y, clamped_w, clamped_h)
    }
}

/// Resolves standard path for window state JSON under an application directory.
///
/// Available when the `serde` feature is enabled.
#[cfg(feature = "serde")]
pub fn get_window_state_path(app_data_root: &Path, app_name: &str, window_name: &str) -> PathBuf {
    app_data_root
        .join(app_name)
        .join(format!("{}_window_state.json", window_name))
}

/// Saves window geometry atomically to disk via write-and-rename.
///
/// Available when the `serde` feature is enabled.
#[cfg(feature = "serde")]
pub fn save_window_geometry_to_path(
    target_path: &Path,
    geometry: &WindowGeometry,
) -> GuiResult<()> {
    if let Some(parent) = target_path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| GuiError::Backend(format!("Failed to create state dir: {e}")))?;
    }

    let temp_path = target_path.with_extension(format!("tmp.{}", std::process::id()));

    let json_data = serde_json::to_string_pretty(geometry)
        .map_err(|e| GuiError::Backend(format!("Failed to serialize window geometry: {e}")))?;

    {
        let mut file = File::create(&temp_path)
            .map_err(|e| GuiError::Backend(format!("Failed to create temp state file: {e}")))?;
        file.write_all(json_data.as_bytes())
            .map_err(|e| GuiError::Backend(format!("Failed to write temp state file: {e}")))?;
        file.sync_all()
            .map_err(|e| GuiError::Backend(format!("Failed to sync temp state file: {e}")))?;
    }

    fs::rename(&temp_path, target_path)
        .map_err(|e| GuiError::Backend(format!("Failed to atomically replace state file: {e}")))?;

    Ok(())
}

/// Loads window geometry from disk, validating against connected displays.
///
/// Falls back safely to default geometry if file is missing, corrupt, or invalid.
/// Available when the `serde` feature is enabled.
#[cfg(feature = "serde")]
pub fn load_window_geometry_from_path(
    target_path: &Path,
    displays: &[DisplayInfo],
) -> WindowGeometry {
    if !target_path.exists() {
        return WindowGeometry::default();
    }

    let content = match fs::read_to_string(target_path) {
        Ok(c) => c,
        Err(_) => return WindowGeometry::default(),
    };

    let parsed: WindowGeometry = match serde_json::from_str(&content) {
        Ok(g) => g,
        Err(_) => return WindowGeometry::default(),
    };
    if parsed.schema_version != 1 {
        return WindowGeometry::default();
    }

    let clamped_bounds = clamp_to_displays(&parsed.floating_bounds, displays, 32);

    WindowGeometry {
        show_state: parsed.show_state,
        floating_bounds: clamped_bounds,
        display_id: parsed.display_id,
        schema_version: 1,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::displays::DisplayRect;

    fn sample_displays() -> Vec<DisplayInfo> {
        vec![
            DisplayInfo {
                id: 1,
                name: "Primary Display".to_string(),
                bounds: DisplayRect {
                    x: 0,
                    y: 0,
                    width: 1920,
                    height: 1080,
                },
                work_area: DisplayRect {
                    x: 0,
                    y: 40,
                    width: 1920,
                    height: 1040,
                },
                scale_factor: 1.0,
                primary: true,
            },
            DisplayInfo {
                id: 2,
                name: "Secondary Display".to_string(),
                bounds: DisplayRect {
                    x: 1920,
                    y: 0,
                    width: 1920,
                    height: 1080,
                },
                work_area: DisplayRect {
                    x: 1920,
                    y: 0,
                    width: 1920,
                    height: 1080,
                },
                scale_factor: 1.0,
                primary: false,
            },
        ]
    }

    #[test]
    fn default_geometry_invariants() {
        let geom = WindowGeometry::default();
        assert_eq!(geom.show_state, WindowShowState::Normal);
        assert_eq!(geom.floating_bounds.width, 800);
        assert_eq!(geom.floating_bounds.height, 600);
        assert_eq!(geom.schema_version, 1);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn serialization_round_trip() {
        let geom = WindowGeometry::new_maximized(120, 150, 1024, 768);
        let serialized = serde_json::to_string(&geom).expect("serialize");
        let deserialized: WindowGeometry = serde_json::from_str(&serialized).expect("deserialize");
        assert_eq!(geom, deserialized);
    }

    #[test]
    fn clamp_within_primary_work_area() {
        let displays = sample_displays();
        let req = RectGeometry::new(100, 20, 800, 600); // y: 20 is above work_area.y: 40
        let clamped = clamp_to_displays(&req, &displays, 30);
        assert_eq!(clamped.y, 40); // Clamped down so titlebar is visible
        assert_eq!(clamped.x, 100);
        assert_eq!(clamped.width, 800);
        assert_eq!(clamped.height, 600);
    }

    #[test]
    fn clamp_secondary_display_when_connected() {
        let displays = sample_displays();
        let req = RectGeometry::new(2000, 100, 800, 600);
        let clamped = clamp_to_displays(&req, &displays, 30);
        assert_eq!(clamped.x, 2000);
        assert_eq!(clamped.y, 100);
    }

    #[test]
    fn clamp_keeps_a_position_only_when_enough_titlebar_is_grabbable() {
        // Primary only: a sliver would otherwise legitimately belong to the
        // neighbouring display.
        let displays = vec![sample_displays()[0].clone()];
        // A 1 px sliver of the titlebar is on the primary work area: not a
        // usable grab strip, so the window recovers to a centered position.
        let req = RectGeometry::new(1919, 100, 800, 600);
        let clamped = clamp_to_displays(&req, &displays, 30);
        assert_ne!(clamped.x, 1919, "a sliver must not count as visible");
        assert!(clamped.x >= 0 && clamped.x < 1920);
        assert!(clamped.y >= 40);

        // 120 px of the titlebar is visible: enough to grab.
        let req = RectGeometry::new(1800, 100, 800, 600);
        let clamped = clamp_to_displays(&req, &displays, 30);
        assert_eq!(clamped.x, 1800);
    }

    #[test]
    fn clamp_off_screen_disconnected_monitor_recovers_to_primary() {
        let displays = vec![sample_displays()[0].clone()]; // Only primary connected
        let req = RectGeometry::new(2500, 200, 800, 600); // Was on secondary
        let clamped = clamp_to_displays(&req, &displays, 30);
        // Should center within primary work area (1920x1040, starting at y=40)
        assert!(clamped.x >= 0 && clamped.x < 1920);
        assert!(clamped.y >= 40 && clamped.y < 1080);
        assert_eq!(clamped.width, 800);
        assert_eq!(clamped.height, 600);
    }

    #[test]
    fn ensure_minimum_size_clamps_small_values() {
        let req = RectGeometry::new(50, 50, 50, 20);
        let safe = req.ensure_minimum_size();
        assert_eq!(safe.width, RectGeometry::MIN_WIDTH);
        assert_eq!(safe.height, RectGeometry::MIN_HEIGHT);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn atomic_save_and_load_round_trip() {
        let temp_dir =
            std::env::temp_dir().join(format!("native_gui_test_geom_{}", std::process::id()));
        let state_path = temp_dir.join("test_window_state.json");
        let displays = sample_displays();

        let original = WindowGeometry::new_floating(150, 180, 900, 650);
        save_window_geometry_to_path(&state_path, &original).expect("save should succeed");

        let loaded = load_window_geometry_from_path(&state_path, &displays);
        assert_eq!(loaded.show_state, original.show_state);
        assert_eq!(loaded.floating_bounds, original.floating_bounds);

        // Corrupted file handling
        fs::write(&state_path, "invalid json content").expect("write corrupt");
        let fallback = load_window_geometry_from_path(&state_path, &displays);
        assert_eq!(fallback, WindowGeometry::default());

        let _ = fs::remove_dir_all(&temp_dir);
    }
}