AstrBot-Desktop/src-tauri/src/quick_window.rs

108 行
2.7 KiB
Rust

use serde::{Deserialize, Serialize};
pub const QUICK_WINDOW_ID: &str = "quick-chat";
pub const DEFAULT_WIDTH: u32 = 420;
pub const DEFAULT_HEIGHT: u32 = 620;
pub const MIN_WIDTH: u32 = 320;
pub const MIN_HEIGHT: u32 = 420;
pub const MAX_WIDTH: u32 = 900;
pub const MAX_HEIGHT: u32 = 1200;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuickWindowState {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
pub monitor_name: Option<String>,
}
impl Default for QuickWindowState {
fn default() -> Self {
Self {
x: 0,
y: 0,
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
monitor_name: None,
}
}
}
impl QuickWindowState {
pub fn normalized(mut self) -> Self {
self.width = self.width.clamp(MIN_WIDTH, MAX_WIDTH);
self.height = self.height.clamp(MIN_HEIGHT, MAX_HEIGHT);
self
}
pub fn clamp_to_work_area(
mut self,
area_x: i32,
area_y: i32,
area_width: u32,
area_height: u32,
) -> Self {
self = self.normalized();
let width = self.width.min(area_width.max(MIN_WIDTH));
let height = self.height.min(area_height.max(MIN_HEIGHT));
let max_x = area_x + area_width.saturating_sub(width) as i32;
let max_y = area_y + area_height.saturating_sub(height) as i32;
self.width = width;
self.height = height;
self.x = self.x.clamp(area_x, max_x.max(area_x));
self.y = self.y.clamp(area_y, max_y.max(area_y));
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_invalid_size() {
let state = QuickWindowState {
x: 10,
y: 20,
width: 1,
height: 50_000,
monitor_name: None,
}
.normalized();
assert_eq!(state.width, MIN_WIDTH);
assert_eq!(state.height, MAX_HEIGHT);
}
#[test]
fn clamps_position_to_work_area() {
let state = QuickWindowState {
x: -900,
y: 9000,
width: 500,
height: 600,
monitor_name: Some("DISPLAY1".into()),
}
.clamp_to_work_area(100, 200, 1600, 900);
assert_eq!(state.x, 100);
assert_eq!(state.y, 500);
assert_eq!(state.monitor_name.as_deref(), Some("DISPLAY1"));
}
#[test]
fn shrinks_window_when_work_area_is_smaller_than_limits() {
let state = QuickWindowState {
width: MAX_WIDTH,
height: MAX_HEIGHT,
..Default::default()
}
.clamp_to_work_area(0, 0, 360, 460);
assert_eq!(state.width, 360);
assert_eq!(state.height, 460);
}
}