ailloli_ui_winit/
window.rs

1//! Window creation: all paths go through [`window_attributes`] / [`create_window`].
2
3use ailloli_ui_core::{AppIcon, Size};
4#[cfg(feature = "native_overlay")]
5use winit::dpi::LogicalPosition;
6use winit::dpi::{LogicalSize, PhysicalSize};
7use winit::event_loop::ActiveEventLoop;
8use winit::event_loop::EventLoop;
9#[cfg(feature = "native_overlay")]
10use winit::window::WindowLevel;
11use winit::window::{Window, WindowAttributes};
12
13#[cfg(feature = "native_overlay")]
14use crate::native_overlay::NativeOverlayOptions;
15
16/// Host-neutral options used to build a native winit window.
17///
18/// [`Default`] creates a visible, decorated, resizable window titled
19/// `"Ailloli UI"`, with no requested size, application identity, icon, client
20/// title row, or native overlay. Logical sizes and radii use Ailloli UI logical
21/// pixels; the operating system chooses physical pixels from the monitor scale.
22///
23/// # Examples
24///
25/// ```
26/// use ailloli_ui_winit::WindowOptions;
27/// let options = WindowOptions::default();
28/// assert_eq!(options.title, "Ailloli UI");
29/// assert!(options.resizable && options.decorations);
30/// assert!(options.inner_size.is_none());
31/// ```
32#[derive(Debug, Clone)]
33pub struct WindowOptions {
34    /// Stable Ailloli UI id for targeted capture; empty means unspecified.
35    pub logical_window_id: String,
36    /// Native title-bar text; defaults to `"Ailloli UI"`.
37    pub title: String,
38    /// Reverse-DNS application id used for native grouping; `None` omits it.
39    pub application_id: Option<String>,
40    /// Effective app/window icon descriptor; `None` keeps the platform default.
41    pub app_icon: Option<AppIcon>,
42    /// Requested logical client size; `None` lets the window manager choose.
43    pub inner_size: Option<LogicalSize<f64>>,
44    /// Whether the operating system supplies native window decorations.
45    pub decorations: bool,
46    /// Whether the user may resize the window through native affordances.
47    pub resizable: bool,
48    /// `true` when the Ailloli UI root is title row + content (`AilloliUi` / `Custom` chrome).
49    pub has_client_title_row: bool,
50    /// Internal view key for the client title row, when provided by the high-level app facade.
51    pub client_titlebar_key: Option<String>,
52    /// Drag the window from the client title bar (`Window::titlebar_draggable`).
53    pub titlebar_draggable: bool,
54    /// Logical corner radius from `ailloli_ui::Window::radius`; zero is square.
55    pub corner_radius: f32,
56    /// Transparent winit window background (rounded corners + client chrome).
57    pub transparent: bool,
58    /// Whether native visibility is deferred until the first rendered frame.
59    pub start_hidden_until_first_frame: bool,
60    #[cfg(feature = "native_overlay")]
61    /// Native overlay geometry and platform policy; `None` creates a normal window.
62    pub native_overlay: Option<NativeOverlayOptions>,
63}
64
65/// Supplies conservative normal-window defaults without native side effects.
66impl Default for WindowOptions {
67    /// Returns decorated opaque defaults with an empty logical ID and title.
68    fn default() -> Self {
69        Self {
70            logical_window_id: String::new(),
71            title: "Ailloli UI".to_string(),
72            application_id: None,
73            app_icon: None,
74            inner_size: None,
75            decorations: true,
76            resizable: true,
77            has_client_title_row: false,
78            client_titlebar_key: None,
79            titlebar_draggable: true,
80            corner_radius: 0.0,
81            transparent: false,
82            start_hidden_until_first_frame: false,
83            #[cfg(feature = "native_overlay")]
84            native_overlay: None,
85        }
86    }
87}
88
89/// Builder-style host-neutral window configuration.
90impl WindowOptions {
91    /// Sets the initial logical client size without exposing a winit DPI type to
92    /// provider-neutral callers.
93    ///
94    /// Each component is clamped to at least `1.0` logical pixel. `NaN` also
95    /// becomes `1.0`; positive infinity remains infinite and may later be
96    /// rejected by the platform.
97    ///
98    /// # Examples
99    ///
100    /// ```
101    /// use ailloli_ui_core::Size;
102    /// use ailloli_ui_winit::WindowOptions;
103    /// let options = WindowOptions::default()
104    ///     .with_logical_inner_size(Size::new(0.0, 480.0));
105    /// let size = options.inner_size.unwrap();
106    /// assert_eq!((size.width, size.height), (1.0, 480.0));
107    /// ```
108    pub fn with_logical_inner_size(mut self, size: Size) -> Self {
109        self.inner_size = Some(LogicalSize::new(
110            size.w.max(1.0) as f64,
111            size.h.max(1.0) as f64,
112        ));
113        self
114    }
115}
116
117/// Builds winit [`WindowAttributes`] from Ailloli UI options without creating a window.
118///
119/// Native overlays override transparency, decorations, resizing, activation,
120/// z-level, position, and size so their geometry remains authoritative. On
121/// Linux, `application_id` is forwarded to both Wayland and X11 attributes.
122/// Invalid icon rasterization is ignored and leaves the platform icon unset.
123///
124/// # Examples
125///
126/// ```
127/// use ailloli_ui_winit::{window_attributes, WindowOptions};
128/// let attributes = window_attributes(&WindowOptions {
129///     title: "Inspector".into(),
130///     start_hidden_until_first_frame: true,
131///     ..WindowOptions::default()
132/// });
133/// assert_eq!(attributes.title, "Inspector");
134/// assert!(!attributes.visible);
135/// ```
136pub fn window_attributes(options: &WindowOptions) -> WindowAttributes {
137    let mut a = WindowAttributes::default()
138        .with_title(options.title.clone())
139        .with_decorations(options.decorations)
140        .with_resizable(options.resizable)
141        .with_transparent(options.transparent)
142        .with_visible(!options.start_hidden_until_first_frame);
143    if let Some(s) = options.inner_size {
144        a = a.with_inner_size(s);
145    }
146    #[cfg(target_os = "linux")]
147    if let Some(application_id) = options.application_id.as_ref() {
148        a = winit::platform::wayland::WindowAttributesExtWayland::with_name(
149            a,
150            application_id.clone(),
151            application_id.clone(),
152        );
153        a = winit::platform::x11::WindowAttributesExtX11::with_name(
154            a,
155            application_id.clone(),
156            application_id.clone(),
157        );
158    }
159    if let Some(app_icon) = options.app_icon.as_ref() {
160        #[cfg(target_os = "windows")]
161        {
162            if let Some(small_icon) = native_icon(app_icon, 32) {
163                a = a.with_window_icon(Some(small_icon));
164            }
165            if let Some(taskbar_icon) = native_icon(app_icon, 256) {
166                a = winit::platform::windows::WindowAttributesExtWindows::with_taskbar_icon(
167                    a,
168                    Some(taskbar_icon),
169                );
170            }
171        }
172        #[cfg(not(any(target_os = "windows", target_os = "macos")))]
173        if let Some(icon) = native_icon(app_icon, 256) {
174            a = a.with_window_icon(Some(icon));
175        }
176    }
177    #[cfg(feature = "native_overlay")]
178    if let Some(overlay) = &options.native_overlay {
179        let rect = overlay.target.logical_rect;
180        a = a
181            .with_transparent(true)
182            .with_decorations(false)
183            .with_resizable(false)
184            .with_active(false)
185            .with_window_level(WindowLevel::AlwaysOnTop)
186            .with_position(LogicalPosition::new(rect.x, rect.y))
187            .with_inner_size(LogicalSize::new(rect.width, rect.height));
188        #[cfg(target_os = "linux")]
189        {
190            use winit::platform::x11::{WindowAttributesExtX11, WindowType};
191            a = a.with_x11_window_type(vec![WindowType::Dock]);
192        }
193    }
194    a
195}
196
197#[cfg(not(target_os = "macos"))]
198/// Rasterizes an application icon at `px` square physical pixels.
199///
200/// Rasterization and winit RGBA validation errors are deliberately collapsed
201/// to `None`, allowing window creation to continue with the platform default.
202fn native_icon(icon: &AppIcon, px: u32) -> Option<winit::window::Icon> {
203    let raster = ailloli_ui_icon::rasterize_app_icon(icon, px).ok()?;
204    winit::window::Icon::from_rgba(raster.rgba.to_vec(), raster.width, raster.height).ok()
205}
206
207/// Emits a diagnostic line only when either supported trace variable is present.
208fn trace_window(message: impl std::fmt::Display) {
209    if crate::winit_trace_enabled() {
210        eprintln!("ailloli_ui_winit: {message}");
211    }
212}
213
214/// Restricts an initial logical size to 70% of a known monitor work area.
215///
216/// `scale_factor` is floored to `1.0` before converting physical monitor pixels
217/// to logical pixels. A zero monitor dimension is an unavailable sentinel and
218/// preserves the request. Components are otherwise independently capped and
219/// never reduced below one logical pixel.
220fn constrain_logical_size_for_monitor(
221    size: LogicalSize<f64>,
222    monitor_physical: PhysicalSize<u32>,
223    scale_factor: f64,
224) -> LogicalSize<f64> {
225    let scale_factor = scale_factor.max(1.0);
226    let logical_width = (monitor_physical.width as f64 / scale_factor)
227        .floor()
228        .max(1.0);
229    let logical_height = (monitor_physical.height as f64 / scale_factor)
230        .floor()
231        .max(1.0);
232    trace_window(format_args!(
233        "primary monitor size {}x{} @ {}x, logical max {}x{}, requested window size {}x{}",
234        monitor_physical.width,
235        monitor_physical.height,
236        scale_factor,
237        logical_width,
238        logical_height,
239        size.width,
240        size.height
241    ));
242
243    if monitor_physical.width == 0 || monitor_physical.height == 0 {
244        return size;
245    }
246
247    // Some Linux compositors accept an oversized initial surface, render a frame,
248    // then tear down the display connection instead of negotiating a smaller
249    // configured size. Treat the requested size as preferred and keep startup
250    // windows inside a conservative visible area; users can still resize after
251    // the first frame.
252    let max_width = (logical_width * 0.70).floor().max(1.0);
253    let max_height = (logical_height * 0.70).floor().max(1.0);
254    let constrained = LogicalSize::new(size.width.min(max_width), size.height.min(max_height));
255
256    if constrained != size {
257        trace_window(format_args!(
258            "constrained initial window size to {}x{}",
259            constrained.width, constrained.height
260        ));
261    }
262
263    constrained
264}
265
266/// Applies the monitor clamp using the primary or first available monitor.
267///
268/// If winit reports no monitor, the requested logical size is returned unchanged.
269fn constrain_initial_size(
270    event_loop: &ActiveEventLoop,
271    size: LogicalSize<f64>,
272) -> LogicalSize<f64> {
273    let Some(monitor) = event_loop
274        .primary_monitor()
275        .or_else(|| event_loop.available_monitors().next())
276    else {
277        return size;
278    };
279
280    let monitor_size = monitor.size();
281    constrain_logical_size_for_monitor(size, monitor_size, monitor.scale_factor())
282}
283
284/// Creates a window from an [`ActiveEventLoop`] during normal application resume.
285///
286/// Normal windows with requested sizes are capped to 70% of the primary (or
287/// first available) monitor in logical pixels. Native overlays retain their
288/// exact target rectangle and skip this clamp.
289///
290/// # Errors
291///
292/// Returns winit's platform error when native creation fails.
293///
294/// # Examples
295///
296/// ```no_run
297/// use ailloli_ui_winit::{create_window, WindowOptions};
298/// use winit::event_loop::ActiveEventLoop;
299/// fn open(loop_: &ActiveEventLoop) -> Result<winit::window::Window, winit::error::OsError> {
300///     create_window(loop_, WindowOptions::default())
301/// }
302/// ```
303pub fn create_window(
304    event_loop: &ActiveEventLoop,
305    mut options: WindowOptions,
306) -> Result<Window, winit::error::OsError> {
307    #[cfg(feature = "native_overlay")]
308    let constrain_size = options.native_overlay.is_none();
309    #[cfg(not(feature = "native_overlay"))]
310    let constrain_size = true;
311    if constrain_size {
312        if let Some(size) = options.inner_size {
313            options.inner_size = Some(constrain_initial_size(event_loop, size));
314        }
315    }
316    event_loop.create_window(window_attributes(&options))
317}
318
319/// For tests / tools that need a window before `run_app`.
320///
321/// Uses deprecated [`EventLoop::create_window`]; centralized here to limit warnings
322/// and keep a single framework layer. Unlike [`create_window`], this path does
323/// not constrain a requested initial size to the current monitor.
324///
325/// # Errors
326///
327/// Returns winit's platform error when native creation fails.
328///
329/// # Examples
330///
331/// ```no_run
332/// use ailloli_ui_winit::{create_window_before_run, WindowOptions};
333/// use winit::event_loop::EventLoop;
334/// fn open(loop_: &EventLoop<()>) -> Result<winit::window::Window, winit::error::OsError> {
335///     create_window_before_run(loop_, WindowOptions::default())
336/// }
337/// ```
338#[allow(deprecated)]
339pub fn create_window_before_run(
340    event_loop: &EventLoop<()>,
341    options: WindowOptions,
342) -> Result<Window, winit::error::OsError> {
343    event_loop.create_window(window_attributes(&options))
344}
345
346#[cfg(test)]
347/// Logical-size, attribute forwarding, icon, and overlay invariant scenarios.
348mod tests {
349    use super::*;
350
351    #[test]
352    fn initial_size_clamp_keeps_units_logical_at_dpr_1() {
353        let requested = LogicalSize::new(1200.0, 800.0);
354        let monitor = PhysicalSize::new(1920, 1080);
355        let constrained = constrain_logical_size_for_monitor(requested, monitor, 1.0);
356
357        assert_eq!(constrained, LogicalSize::new(1200.0, 756.0));
358    }
359
360    #[test]
361    fn initial_size_clamp_does_not_apply_dpr_twice() {
362        let requested = LogicalSize::new(1200.0, 800.0);
363        let monitor = PhysicalSize::new(3840, 2160);
364        let constrained = constrain_logical_size_for_monitor(requested, monitor, 2.0);
365
366        assert_eq!(constrained, LogicalSize::new(1200.0, 756.0));
367    }
368
369    #[test]
370    fn window_attributes_forwards_transparent_flag() {
371        let mut o = WindowOptions {
372            transparent: true,
373            ..Default::default()
374        };
375        let a = window_attributes(&o);
376        assert!(a.transparent);
377        o.transparent = false;
378        let a = window_attributes(&o);
379        assert!(!a.transparent);
380    }
381
382    #[test]
383    fn window_attributes_include_a_valid_application_icon() {
384        static SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10" fill="red"/></svg>"#;
385        let options = WindowOptions {
386            application_id: Some("org.example.app".to_string()),
387            app_icon: Some(AppIcon::from_static_svg(SVG, "icon.svg")),
388            ..Default::default()
389        };
390        let attributes = window_attributes(&options);
391        #[cfg(not(target_os = "macos"))]
392        assert!(attributes.window_icon.is_some());
393        #[cfg(target_os = "macos")]
394        assert!(attributes.window_icon.is_none());
395    }
396
397    #[cfg(feature = "native_overlay")]
398    #[test]
399    fn window_overlay_attributes_enforce_native_invariants() {
400        use crate::{NativeOverlayOptions, NativeOverlayRect, NativeOverlayTarget};
401
402        let options = WindowOptions {
403            native_overlay: Some(NativeOverlayOptions::new(NativeOverlayTarget::new(
404                NativeOverlayRect::new(-1280.0, 0.0, 1280.0, 720.0),
405            ))),
406            decorations: true,
407            resizable: true,
408            transparent: false,
409            ..Default::default()
410        };
411        let attributes = window_attributes(&options);
412        assert!(attributes.transparent);
413        assert!(!attributes.decorations);
414        assert!(!attributes.resizable);
415        assert!(!attributes.active);
416        assert_eq!(attributes.window_level, WindowLevel::AlwaysOnTop);
417        assert_eq!(
418            attributes.position,
419            Some(LogicalPosition::new(-1280.0, 0.0).into())
420        );
421        assert_eq!(
422            attributes.inner_size,
423            Some(LogicalSize::new(1280.0, 720.0).into())
424        );
425    }
426}