Skip to main content

slint_borderless/
lib.rs

1//! Windows-native borderless frame support for Slint.
2//!
3//! This crate removes the visible Win32 non-client frame without turning the
4//! window into `WS_POPUP`. Windows therefore remains responsible for resize,
5//! minimize/maximize animations, Aero Snap, `Win + Arrow`, the system menu,
6//! task switching, and the Windows 11 Snap Layout flyout.
7//!
8//! The normal entry point is [`FrameController::attach`].
9
10use std::{error::Error, fmt, rc::Rc};
11
12use slint::ComponentHandle;
13
14#[cfg(not(target_os = "windows"))]
15mod unsupported;
16#[cfg(target_os = "windows")]
17mod windows;
18
19#[cfg(not(target_os = "windows"))]
20use unsupported as platform;
21#[cfg(target_os = "windows")]
22use windows as platform;
23
24/// Which system caption button is under the pointer.
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
26pub enum CaptionButton {
27    Minimize,
28    Maximize,
29    Close,
30}
31
32impl CaptionButton {
33    /// Value expected by the bundled `Win32TitleBar.hover-button` property.
34    pub const fn slint_value(self) -> i32 {
35        match self {
36            Self::Minimize => 1,
37            Self::Maximize => 2,
38            Self::Close => 3,
39        }
40    }
41}
42
43/// Notifications emitted by the native frame.
44#[derive(Clone, Debug, Eq, PartialEq)]
45pub enum FrameEvent {
46    Installed,
47    CaptionHoverChanged(Option<CaptionButton>),
48    Detached,
49    Failed(FrameError),
50}
51
52/// A logical point in Slint device-independent pixels.
53#[derive(Clone, Copy, Debug, Default, PartialEq)]
54pub struct LogicalPoint {
55    pub x: f32,
56    pub y: f32,
57}
58
59/// A logical size in Slint device-independent pixels.
60#[derive(Clone, Copy, Debug, Default, PartialEq)]
61pub struct LogicalSize {
62    pub width: f32,
63    pub height: f32,
64}
65
66/// The edge from which a title-bar client area is positioned.
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum HorizontalAnchor {
69    Left,
70    Right,
71}
72
73/// A rectangle in the custom title bar that remains a Slint client area.
74///
75/// Use this for menus, search fields, tabs, or arbitrary buttons placed in the
76/// title bar. Outside these areas, the title bar drags the window.
77#[derive(Clone, Copy, Debug, PartialEq)]
78pub struct ClientArea {
79    pub anchor: HorizontalAnchor,
80    pub origin: LogicalPoint,
81    pub size: LogicalSize,
82}
83
84impl ClientArea {
85    pub const fn left(x: f32, y: f32, width: f32, height: f32) -> Self {
86        Self {
87            anchor: HorizontalAnchor::Left,
88            origin: LogicalPoint { x, y },
89            size: LogicalSize { width, height },
90        }
91    }
92
93    pub const fn right(x: f32, y: f32, width: f32, height: f32) -> Self {
94        Self {
95            anchor: HorizontalAnchor::Right,
96            origin: LogicalPoint { x, y },
97            size: LogicalSize { width, height },
98        }
99    }
100}
101
102/// Geometry and behavior of the native borderless frame.
103#[derive(Clone, Debug)]
104pub struct FrameOptions {
105    /// Height of the Slint-drawn title bar in logical pixels.
106    pub titlebar_height: f32,
107    /// Width of each of the three system caption buttons in logical pixels.
108    pub caption_button_width: f32,
109    /// Minimum outer window size in logical pixels. `None` keeps Slint's limit.
110    pub minimum_size: Option<LogicalSize>,
111    /// Ask DWM for Windows 11 rounded corners. Ignored on older Windows.
112    pub rounded_corners: bool,
113    /// Interactive Slint controls located inside the title bar.
114    pub client_areas: Vec<ClientArea>,
115}
116
117impl Default for FrameOptions {
118    fn default() -> Self {
119        Self {
120            titlebar_height: 48.0,
121            caption_button_width: 46.0,
122            minimum_size: None,
123            rounded_corners: true,
124            client_areas: Vec::new(),
125        }
126    }
127}
128
129/// Errors returned while attaching or detaching a frame.
130#[derive(Clone, Debug, Eq, PartialEq)]
131pub enum FrameError {
132    UnsupportedPlatform,
133    RenderingNotifierUnavailable(String),
134    WindowHandleUnavailable(String),
135    NotAWin32Window,
136    InvalidOptions,
137    AlreadyAttached,
138    NativeSubclassFailed,
139    NativeDetachFailed,
140}
141
142impl fmt::Display for FrameError {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        match self {
145            Self::UnsupportedPlatform => f.write_str("slint-borderless only supports Windows"),
146            Self::RenderingNotifierUnavailable(error) => {
147                write!(f, "Slint rendering notifier is unavailable: {error}")
148            }
149            Self::WindowHandleUnavailable(error) => {
150                write!(f, "native window handle is unavailable: {error}")
151            }
152            Self::NotAWin32Window => f.write_str("Slint did not create a Win32 window"),
153            Self::InvalidOptions => f.write_str("frame dimensions must be finite and positive"),
154            Self::AlreadyAttached => f.write_str("a frame is already attached"),
155            Self::NativeSubclassFailed => f.write_str("SetWindowSubclass failed"),
156            Self::NativeDetachFailed => f.write_str("RemoveWindowSubclass failed"),
157        }
158    }
159}
160
161impl Error for FrameError {}
162
163/// A UI-thread controller for one Slint window.
164///
165/// The controller intentionally is not `Send` or `Sync`: Slint windows and
166/// Win32 subclass operations belong to the UI thread. Cloning it is cheap.
167#[derive(Clone)]
168pub struct FrameController {
169    inner: Rc<platform::FrameInner>,
170}
171
172impl FrameController {
173    /// Attach automatically during Slint's first `RenderingSetup` callback.
174    ///
175    /// This is the one-line API for normal applications. It occupies Slint's
176    /// rendering notifier for this window; use [`Self::attach_window`] if the
177    /// application already owns that notifier.
178    pub fn attach<C: ComponentHandle + 'static>(
179        component: &C,
180        options: FrameOptions,
181    ) -> Result<Self, FrameError> {
182        platform::attach(component, options).map(|inner| Self { inner })
183    }
184
185    /// Attach immediately to an already-created Slint window.
186    ///
187    /// Call this from the application's own `RenderingSetup` notifier when it
188    /// needs to keep using that notifier for custom rendering.
189    pub fn attach_window(
190        window: &slint::Window,
191        options: FrameOptions,
192    ) -> Result<Self, FrameError> {
193        platform::attach_window(window, options).map(|inner| Self { inner })
194    }
195
196    /// Receive hover/install/detach events. Replaces the previous handler.
197    pub fn on_event(&self, handler: impl Fn(FrameEvent) + 'static) {
198        self.inner.set_event_handler(Some(Rc::new(handler)));
199    }
200
201    /// Remove the event handler.
202    pub fn clear_event_handler(&self) {
203        self.inner.set_event_handler(None);
204    }
205
206    /// Replace interactive Slint areas in the title bar.
207    pub fn set_client_areas(&self, areas: impl Into<Vec<ClientArea>>) {
208        self.inner.set_client_areas(areas.into());
209    }
210
211    /// Current caption-button hover state.
212    pub fn caption_hover(&self) -> Option<CaptionButton> {
213        self.inner.caption_hover()
214    }
215
216    /// Whether the Win32 frame is currently installed.
217    pub fn is_attached(&self) -> bool {
218        self.inner.is_attached()
219    }
220
221    /// Most recent asynchronous installation error, if any.
222    pub fn last_error(&self) -> Option<FrameError> {
223        self.inner.last_error()
224    }
225
226    /// Restore the normal Windows non-client frame and remove the subclass.
227    pub fn detach(&self) -> Result<(), FrameError> {
228        self.inner.detach()
229    }
230}
231
232pub(crate) type EventHandler = Rc<dyn Fn(FrameEvent)>;
233
234/// Name used with Slint's `@library` import syntax.
235pub const SLINT_LIBRARY_NAME: &str = "slint-borderless";
236
237/// Filesystem location of the bundled Slint component library.
238///
239/// Call this from `build.rs` and pass it to
240/// `slint_build::CompilerConfiguration::with_library_paths`.
241pub fn slint_library_path() -> std::path::PathBuf {
242    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui")
243}