headless_webview/
window.rs

1use crate::types::WindowSize;
2use crate::webview::EngineWebview;
3use crate::Result;
4
5#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
6pub struct WindowId(pub u32);
7
8/// Represents an underlying (headless) window
9pub trait HeadlessWindow {
10    type NativeWindow;
11    type Webview: EngineWebview<Window = Self>;
12
13    // Create a new window
14    fn new(native_window: Self::NativeWindow, attributes: WindowAttributes) -> Result<Self>
15    where
16        Self: Sized;
17
18    // Get window ID
19    fn id(&self) -> WindowId;
20
21    // Return the window size
22    fn inner_size(&self) -> WindowSize;
23
24    // Return window width
25    fn width(&self) -> u32 {
26        self.inner_size().width
27    }
28
29    // Return window height
30    fn height(&self) -> u32 {
31        self.inner_size().height
32    }
33
34    // Resize the window
35    fn resize(&self, new_size: WindowSize) -> Result<()>;
36}
37
38#[derive(Debug, Clone, Default)]
39pub struct WindowAttributes {
40    pub inner_size: Option<WindowSize>,
41    pub transparent: bool,
42}
43
44impl WindowAttributes {
45    pub fn get_inner_size(&self) -> WindowSize {
46        self.inner_size
47            .as_ref()
48            .map(|v| v.clone())
49            .unwrap_or(WindowSize::default())
50    }
51}
52
53pub struct WindowBuilder<T: HeadlessWindow> {
54    attributes: WindowAttributes,
55    inner: T::NativeWindow,
56    before_build_fn:
57        Option<fn(T::NativeWindow, WindowAttributes) -> (T::NativeWindow, WindowAttributes)>,
58}
59
60impl<T: HeadlessWindow> WindowBuilder<T> {
61    pub fn new(window: T::NativeWindow) -> Self {
62        Self {
63            attributes: Default::default(),
64            inner: window,
65            before_build_fn: None,
66        }
67    }
68
69    pub fn add_before_build_fn(
70        mut self,
71        before_build_fn: fn(
72            T::NativeWindow,
73            WindowAttributes,
74        ) -> (T::NativeWindow, WindowAttributes),
75    ) -> Self {
76        self.before_build_fn = Some(before_build_fn);
77        self
78    }
79
80    pub fn with_inner_size(mut self, inner_size: WindowSize) -> Self {
81        self.attributes.inner_size = Some(inner_size);
82        self
83    }
84
85    pub fn with_transparent(mut self, transparent: bool) -> Self {
86        self.attributes.transparent = transparent;
87        self
88    }
89
90    pub fn build(self) -> Result<T> {
91        if let Some(bfn) = self.before_build_fn {
92            let (inner, attributes) = bfn(self.inner, self.attributes);
93            Ok(T::new(inner, attributes)?)
94        } else {
95            Ok(T::new(self.inner, self.attributes)?)
96        }
97    }
98}